简体   繁体   English

如何在python中查询字典中的值?

[英]How to query values in a dictionary of a dictionary in python?

I have a list in Python and it's a dictionary contains a dictionary. 我有一个Python列表,它是一个包含字典的字典。

{'METTS MARK': {'salary': 365788, 'po': 1}, 'HARRY POTTER':{'salary': 3233233, 'po': 0}

How do I calculate the number of records with 'po' = 1 ? 如何计算'po' = 1的记录数?

I tried this: 我试过这个:

sum = 0
for key, values in DIC:
     if values[po] == 1:
        sum = sum + 1

But it returns: too many values to unpack 但它返回: too many values to unpack

Thanks in advance 提前致谢

You can simply use sum and sum over the condition: 你可以简单地使用sum和求和的条件:

total = sum(values.get('po') == 1 for values in DIC.values())

which is equivalent to (as @VPfB says): 这相当于(如@VPfB所说):

total = sum (1 for item in DIC.values() if item.get('po') == 1)

but the latter is a bit less efficient. 但后者的效率稍差。

You should also use 'po' instead of po since it is a string, and you better use .get('po') since this guarantees that it will work if 'po' is not part of every dictionary. 你也应该使用'po'代替po因为它是一个字符串,你最好使用.get('po')因为这可以保证如果'po'不是每个字典的一部分,它将起作用。

I think you forgot to use .items() in your for loop . 我想你忘了在for循环中使用.items() By iterating over the dictionary, you iterate over the keys and in this case, you cannot unpack your keys into tuples with two elements. 通过迭代字典,您迭代 ,在这种情况下,您不能将键解包为具有两个元素的元组。

Nevertheless using a generator, this will be more memory efficient (probably faster as well) and it is clean code. 尽管如此,使用生成器,这将是更高效的内存(可能更快),它是干净的代码。 Furthermore by iterating directly over the .values instead of the .items one expects an increase in performance because one saves on packing and unpacking. 此外,通过直接迭代.values而不是.items人们期望性能提高,因为可以节省打包.items包。

You can get it like this: 你可以这样得到它:

a = {
     'METTS MARK': {'salary': 365788, 'po': 1},
     'HARRY POTTER': {'salary': 3233233, 'po': 0}
     }

print(len([b for b in a.values() if b.get('po')==1]))

Output: 输出:

1

Here we are creating a list of dictionaries where the key po==1 . 这里我们创建一个字典列表,其中键po==1 And then we calculate the length of the list. 然后我们计算列表的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM