[英]iterate through a dictionary inside a dictionary in python
So let's say i have 所以说我有
dictionary = {
'Moe': {
'name':'moe',
'age':24,
'married':False
},
'Jon': {
'name':'jon',
'age':22,
'married':False
},
'andrew':
{'name':'andrew',
'age':27,
'married':True
}
}
Suppose that i want to iterate through the dictionary to find out how many person is married in this dictionary, how can i do it? 假设我想遍历字典以找出这本字典中有多少人结婚,我该怎么办?
You could use the following generator comprehension to lookup married
in the inner dictionaries setting the default value to 0
, and take the sum
: 您可以使用以下生成器理解在内部字典中查找
married
,并将默认值设置为0
,然后sum
:
sum(i.get('married', 0) for i in dictionary.values())
#1
You need: 你需要:
count = 0
for v in dictionary.values():
if v['married']:
count += 1
print(count)
One way of doing it is like this: 一种方法是这样的:
n_married = 0
for key, item in d.items():
name, age, married = item
n_married += 1 if married else 0
print(n_married)
result = 0 for x in dictionary: if dictionary[x]['married'] == True: result += 1 print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.