在嵌套的Python词典中搜索键

在嵌套的Python词典中搜索键,第1张

嵌套的Python词典中搜索键

你近了

idnum = 11# The loop and 'if' are good# You just had the 'break' in the wrong placefor id, idnumber in A.iteritems():    if idnum in idnumber.keys(): # you can skip '.keys()', it's the default       calculate = some_function_of(idnumber[idnum])       break # if we find it we're done looking - leave the loop    # otherwise we continue to the next dictionaryelse:    # this is the for loop's 'else' clause    # if we don't find it at all, we end up here    # because we never broke out of the loop    calculate = your_default_value    # or whatever you want to do if you don't find it

如果您需要知道

11
内部
dict
s中有多少个作为键,则可以:

idnum = 11print sum(idnum in idnumber for idnumber in A.itervalues())

之所以可行,是因为每个密钥只能进入

dict
一次,因此您只需测试密钥是否退出即可。
in
返回
True
False
等于
1
0
,因此
sum
是的出现次数
idnum



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5623450.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存