【问题标题】:Search for a key in a nested Python dictionary在嵌套 Python 字典中搜索键
【发布时间】:2011-12-02 15:17:23
【问题描述】:

我有一些这样的 Python 字典:

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

例如

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

我需要搜索字典是否有任何idnumber == 11 并用condition 计算一些东西。但是如果整个字典中没有idnumber == 11,我需要继续next字典。

这是我的尝试:

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

【问题讨论】:

标签: python dictionary recursion nested


【解决方案1】:

【讨论】:

  • 这是一个普遍重复的问题,dpath 几乎没有得到足够的认可,尽管它是一个非常简单的解决方案,因此链接到这里以获得更好的曝光。
【解决方案2】:

你已经接近了。

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

如果您需要知道内部dicts 中有多少个11s 作为键,您可以:

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

这是可行的,因为每个dict 中的密钥只能出现一次,因此您只需要测试密钥是否退出。 in 返回TrueFalse 等于10,所以sumidnum 的出现次数。

【讨论】:

  • 嗨@agf 感谢您的帮助。顺便说一句,如果我想计算 idnumber 中 11 的个数该怎么办?谢谢!!! :)
  • 我不确定您的问题? idnumber 是一个dictidnum 是那个dict 中的一个键,所以每个idnumber 中只能有一个idnum。如果您的意思是具有 11s 作为键的 idnumber 字典的总数,我会将其添加到我的答案中。
  • 对不起,我没有正确解释。这些字典的 id 就像对每个 idnumber 的计数,即像这样{1: {15: 67.4}, 2: {13: 78.4}, 3: {11 : 723.73}, 4: {11 : 34.21}... 所以我需要计算每个字典中的所有 idnumber 中有多少 11。谢谢你的时间!!! :)
  • @Alejandro 这就是我添加到答案底部的代码的作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
  • 2016-12-16
  • 1970-01-01
  • 2020-10-01
  • 2016-08-16
  • 2021-11-21
  • 2023-02-10
相关资源
最近更新 更多