简体   繁体   English

如何从词典列表中的特定键中获取唯一值?

[英]How to get unique values from a specific key in a list of dictionaries?

Give I have a list with dictionaries and I want to get all unique values from the key first_name from the dictionaries, how do I do that in python? 给我一个包含字典的列表,我想从字典的first_name键中获取所有唯一值,如何在python中做到这一点?

data = [
{
    "id": 1,
    "first_name": "John"
},
{   "id": 2,
    "first_name": "Mary"
},
{   "id": 3,
    "first_name": "John"
}
]

您可以使用set comprehension

first_names = {d["first_name"] for d in data}
>>> set(i["first_name"] for i in data)
{'John', 'Mary'}

if you want a list instead of set you can convert it to list: 如果你想有一个list ,而不是set ,你可以将其转换为列表:

>>> list(set(i["first_name"] for i in data))
['John', 'Mary']

You can map the operator itemgetter() to dictionaries in the list: 您可以将运算符itemgetter()映射到列表中的字典:

from operator import itemgetter

iget = itemgetter('first_name')

set(map(iget, data))
# {'Mary', 'John'}

暂无
暂无

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

相关问题 如何在字典列表中找到特定键的唯一值? - How do I find unique values for a specific key in a list of dictionaries? 如何为字典列表中的特定键获取一组唯一的值? - How do I get a unique set of values for a specific key in a list of dictionaries? 如何根据两个列表字典中特定键的comman值从两个字典列表中获取comman数据? - How to get comman data from two list of dictionaries based on having comman values for a specific key in both list's dictionaries? 如何插入到特定键中的字典值列表 - How to insert to a list of dictionaries values in a specific key 如何从多个字典列表中获取特定值 - How to get specific values from a list of multiple dictionaries 获取嵌套字典列表中特定键的所有值的列表 - Get list of all values for a specific key in a list of nested dictionaries 如何根据所有词典中都不存在的特定键值从词典列表中获取值? - How to get value from list of dictionaries based on specific key value which does not exist in all dictionaries? 根据单独的列表更新词典列表中特定键的值 - Updating values from specific key in list of dictionaries based on a separate list Python:字典列表,如何获取列表中多个项目的特定键的值? - Python: list of dictionaries, how to get values of a specific key for multiple items of the list? 如何将具有相同键的词典值合并到词典列表中? - How to merge values of dictionaries with same key into one from a list of dictionaries?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM