在嵌套 Python 字典中搜索键
我有一些像这样的Python字典:
A = {id: {idnumber: condition},....
例如,
A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....
我需要搜索字典是否有idnumber == 11
并使用条件
计算一些内容。但如果整个字典中没有任何 idnumber == 11
,我需要继续使用下一个字典。
这是我的尝试:
for id, idnumber in A.iteritems():
if 11 in idnumber.keys():
calculate = ......
else:
break
I have some Python dictionaries like this:
A = {id: {idnumber: condition},....
e.g.
A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....
I need to search if the dictionary has any idnumber == 11
and calculate something with the condition
. But if in the entire dictionary doesn't have any idnumber == 11
, I need to continue with the next dictionary.
This is my try:
for id, idnumber in A.iteritems():
if 11 in idnumber.keys():
calculate = ......
else:
break
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
dpath 来救援。
http://github.com/akesterson/dpath-python
dpath 允许您按全局搜索,这会让你得到你想要的。
它将迭代字典中的所有条件,因此不需要特殊的循环结构。
另请参阅
dpath to the rescue.
http://github.com/akesterson/dpath-python
dpath lets you search by globs, which will get you what you want.
It will iterate out all of the conditions in the dictionary, so no special looping constructs required.
See also
你很接近了。
如果您需要知道内部
dict
中有多少个11
作为键,您可以:这有效,因为键只能在每个
dict 中
一次,因此您只需测试该键是否存在即可。in
返回True
或False
,它们等于1
和0
,因此sum
是idnum
出现的次数。You're close.
If you need to know how many
11
s there are as keys in the innerdict
s, you can:This works because a key can only be in each
dict
once so you just have to test if the key exits.in
returnsTrue
orFalse
which are equal to1
and0
, so thesum
is the number of occurences ofidnum
.