gpt4 book ai didi

python - 在python中的字典中遍历字典

转载 作者:太空宇宙 更新时间:2023-11-03 11:12:19 24 4
gpt4 key购买 nike

假设我有

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

假设我想遍历字典,找出这个字典中有多少人结婚了,我该怎么做?

最佳答案

您可以使用以下生成器推导式在内部字典中查找 married,将默认值设置为 0,然后获取 sum:

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

关于python - 在python中的字典中遍历字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57990233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com