如何从字典列表中提取特定值?

时间:2021-05-19 09:37:09

标签: python list dictionary

我有一个字典列表,看起来像这样:

[{'Score': 0.9979117512702942, 'Type': 's_merchant', 'Text': 'merchants', 'BeginOffset': 7, 'EndOffset': 16}, {'Score': 0.9997400045394897, 'Type': 'metric', 'Text': 'number of errors', 'BeginOffset': 22, 'EndOffset': 38}, {'Score': 0.9984105825424194, 'Type': 'metric', 'Text': 'order rate', 'BeginOffset': 43, 'EndOffset': 53}, {'Score': 0.997801661491394, 'Type': 'user_service', 'Text': 'search requests', 'BeginOffset': 57, 'EndOffset': 72}, {'Score': 0.999964714050293, 'Type': 'PROPERTY', 'Text': 'revenue', 'BeginOffset': 20, 'EndOffset': 27}, {'Score': 0.999964714050293, 'Type': 'PROPERTY_VAL', 'Text': 'gold', 'BeginOffset': 28, 'EndOffset': 32}, {'Score': 0.9646918177604675, 'Type': 'ORGANIZATION', 'Text': 'Gymshark', 'BeginOffset': 22, 'EndOffset': 30}]

我需要从列表中的所有字典中提取键 'Type'(对于第一个字典基本上是 's_merchant')和 'Text'(对于第一个字典是 'merchants')中的所有值。

输出应该是一个列表,如下所示:

Type=['s_merchant','metric','user_service','PROPERTY','PROPERTY_VAL','ORGANIZATION'] 
Text=['merchants','number of errors','order rate','revenue','gold','Gymshark']

是否有实现此目的的功能/方法? 感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

Type = []
Text = []
for s in list_dicts :
  Type.append(s['Type'])
  Text.append(s['Text'])

或者通过使用理解列表减少代码(但它完全相同):

Type = [s['Type'] for s in list_dicts]
Text = [s['Text'] for s in list_dicts]

答案 1 :(得分:1)

您可以使用 python's list comprehension,它允许比常规循环更紧凑的合成器:

l = [{'Score': 0.9979117512702942, 'Type': 's_merchant', 'Text': 'merchants', 'BeginOffset': 7, 'EndOffset': 16}, {'Score': 0.9997400045394897, 'Type': 'metric', 'Text': 'number of errors', 'BeginOffset': 22, 'EndOffset': 38}, {'Score': 0.9984105825424194, 'Type': 'metric', 'Text': 'order rate', 'BeginOffset': 43, 'EndOffset': 53}, {'Score': 0.997801661491394, 'Type': 'user_service', 'Text': 'search requests', 'BeginOffset': 57, 'EndOffset': 72}, {'Score': 0.999964714050293, 'Type': 'PROPERTY', 'Text': 'revenue', 'BeginOffset': 20, 'EndOffset': 27}, {'Score': 0.999964714050293, 'Type': 'PROPERTY_VAL', 'Text': 'gold', 'BeginOffset': 28, 'EndOffset': 32}, {'Score': 0.9646918177604675, 'Type': 'ORGANIZATION', 'Text': 'Gymshark', 'BeginOffset': 22, 'EndOffset': 30}]


Type = [i['Type'] for i in l]
Text = [i['Text'] for i in l]

要删除列表中的重复值,一个不错的选择是使用 set 对象,例如:

list(set(Type))

以您的示例为例,只需执行以下操作:

Type = list(set([i['Type'] for i in l]))