简体   繁体   English

获取字典中具有特定值的所有键 Python

[英]Get all keys with specific value in dictionary Python

Is it possible to get all the keys matching a specific value from a Python dictionary?是否可以从 Python 字典中获取与特定值匹配的所有键?

For example, I have a dictionary with the following data:例如,我有一本包含以下数据的字典:

dataset = [

        {'name': 'A', 'age': 37, 'gender': 'M'},
        {'name': 'B', 'age': 20, 'gender': 'F'},
        {'name': 'C', 'age': 17, 'gender': 'M'},
        {'name': 'D', 'age': 19, 'gender': 'F'},
        {'name': 'E', 'age': 30, 'gender': 'F'}
    ]

I would like to filter the dictionary and get all the keys where the Gender='F'.我想过滤字典并获取 Gender='F' 的所有键。

I run the below line to filter the key 'Gender' for value 'F'.我运行以下行来过滤值“F”的键“性别”。

res = next((sub for sub in dataset if sub['gender'] == 'F'), None)
print(res)

However, I get only 1 key as output.但是,我只得到 1 个密钥 output。

Output: {'name': 'B', 'age': 27, 'gender': 'F'} Output: {'name': 'B', 'age': 27, 'gender': 'F'}

Want this as output:想要这个作为 output:

{'name': 'B', 'age': 20, 'gender': 'F'}
{'name': 'D', 'age': 19, 'gender': 'F'}
{'name': 'E', 'age': 30, 'gender': 'F'}

Just use conditional list comprehension like this:只需像这样使用条件列表理解:

[i for i in dataset if i['gender'] == 'F']

which should give:这应该给:

[{'name': 'B', 'age': 20, 'gender': 'F'}, {'name': 'D', 'age': 19, 'gender': 'F'}, {'name': 'E', 'age': 30, 'gender': 'F'}]

I am not sure why you have used the next function, but simple list comprehension will do:我不确定你为什么使用下一个 function,但简单的列表理解就可以了:

res = [sub for sub in dataset if sub['gender'] == 'F']

You can also try the following code:您也可以尝试以下代码:

dataset = [{'name': 'A', 'age': 37, 'gender': 'M'}, {'name': 'B', 'age': 20, 'gender': 'F'}, {'name': 'C', 'age': 17, 'gender': 'M'}, {'name': 'D', 'age': 19, 'gender': 'F'},{'name': 'E', 'age': 30, 'gender': 'F'} ]
for i in dataset:
    if i['gender']=='F':
        print(i)

and what about if I want to take every female because I want to check the mean, how you can do it?如果我想取每个女性,因为我想检查平均值,你怎么做? I'm just curious sorry我只是好奇对不起

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

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