在python的字典中遍历字典

2024-04-24 23:00:39 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有

dictionary = {
    'Moe': {
             'name':'moe',
             'age':24,
             'married':False
           },
    'Jon': {
             'name':'jon',
             'age':22,
             'married':False
           },
    'andrew': 
           {'name':'andrew',
            'age':27,
            'married':True
           }
}

假设我想在这本字典里反复查一下有多少人结婚了,我该怎么做呢?你知道吗


Tags: namefalsetrueagedictionary字典jonandrew
3条回答
result = 0
for x in dictionary:
    if dictionary[x]['married'] == True:
        result += 1
print(result)

一种方法是:

n_married = 0 
for key, item in d.items(): 
    name, age, married = item 
    n_married += 1 if married else 0 
print(n_married)

您可以使用以下生成器理解在内部词典中查找married,将默认值设置为0,并采用sum

sum(i.get('married', 0) for i in dictionary.values())
#1

相关问题 更多 >