在嵌套的Python字典中search一个键

我有这样的一些Python字典:

A = {id: {idnumber: condition},.... 

例如

 A = {1: {11 : 567.54}, 2: {14 : 123.13}, ..... 

我需要search,如果字典有任何idnumber == 11并计算与condition东西。 但如果在整个字典中没有任何idnumber == 11 ,我需要继续下一个字典。

这是我的尝试:

 for id, idnumber in A.iteritems(): if 11 in idnumber.keys(): calculate = ...... else: break 

你很近

 idnum = 11 # The loop and 'if' are good # You just had the 'break' in the wrong place for 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 dictionary else: # 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 

如果您需要知道内部dict有多less11键,您可以:

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

这是有效的,因为一个键只能在每个dict一次,所以你只需要testing该键是否退出。 in返回TrueFalse ,它们等于10 ,所以sum就是idnum

dpath去救援。

http://github.com/akesterson/dpath-python

dpath可以让你用globssearch,这会得到你想要的。

 $ easy_install dpath >>> for (path, value) in dpath.util.search(MY_DICT, '*/11', yielded=True): >>> ... # 'value' will contain your condition; now do something with it. 

它将遍历字典中的所有条件,所以不需要特殊的循环结构。

也可以看看

  • 我如何遍历嵌套字典(python)?
  • 如何做到这一点 – python字典遍历和search
  • 通过键列表访问嵌套字典项目?
  • 在嵌套的python字典和列表中查找所有出现的键
  • 遍历一个嵌套的字典,并在Python中获取path?
  • 查找嵌套字典中的所有键和键
  • 在嵌套字典中search键
  • Python:在深度嵌套的字典中更新值
  • 有没有JSON的查询语言?