简体   繁体   English

如何在字典列表中引用和返回值

[英]How to reference and return values in a list of dictionaries

I have a list of lists. 我有一个清单清单。

Inside of each list there are a few thousand lists of dictionaries. 每个列表中有几千个字典列表。 One list might contain multiple dictionaries, one dictionary, or it might be empty. 一个列表可能包含多个词典,一个词典,或者可能为空。

Here is an abridged list with three examples rows in the list: 这是一个简化的列表,列表中包含三个示例行:

list_of_lists = [[], [{'text': 'analytics', 'indices': [18, 28]}, {'text': 'datascience', 'indices': [35, 47]}, {'text': 'restaurants', 'indices': [54, 66]}, {'text': 'machinelearning', 'indices': [92, 108]}, {'text': 'bigData', 'indices': [109, 117]}, {'text': 'CRM', 'indices': [118, 122]}], [{'text': 'python', 'indices': [49, 56]}, {'text': 'datascience', 'indices': [57, 69]}]

So within this list there's one empty list, one list with 6 dictionaries, and one list with 2 dictionaries. 因此,此列表中有一个空列表,一个包含6个字典的列表,以及一个包含2个字典的列表。

I need to extract the value from the key:value pair that includes 'text': 'SOME_STRING'. 我需要从包含'text':'SOME_STRING'的key:value对中提取值。

Also, IMPORTANTLY, each value should return in a list with the same index from the original input list. 同样,重要的是,每个值都应在一个列表中返回,该列表具有与原始输入列表相同的索引。 In other words, for example, for the second list of 6 key:value pairs, all 6 values should be returned in a list at the same index that it was at in the original list_of_lists 换句话说,例如,对于6个key:value对的第二个列表,所有6个值都应以与原始list_of_lists中相同的索引在列表中返回

So here is my desired output from the above example: 因此,这是上述示例中我想要的输出:

list_of_values = [[], ['analytics', 'datascience', 'restaurants', 'machinelearning', 'bigData', 'CRM', 'python'], ['python', 'datascience']]

I have written the code below that almost does what I want. 我在下面编写了几乎可以完成我想要的代码。 It returns a list of all of these strings, but it does not return them at the same index, and it also returns the indices dictionary that I don't want. 它返回所有这些字符串的列表,但不会在相同的索引处返回它们,并且还会返回我不需要的索引字典。

new_list_of_value_lists = []
for line in list_of_lists:
    for dictionary in line:
        for key, value in dictionary.items():
            new_list_of_value_lists.append(value)

Create a different list for each nested list of dicts and append to the parent list. 为每个字典的嵌套列表创建一个不同的列表,然后追加到父列表。 The empty list gets zero iterations so the resulting list stays empty, while the others have their values collected in the list comprehension : 空列表得到零次迭代,因此结果列表保持为空,而其他列表的值则收集在列表推导中

list_of_values = []
for lst in list_of_lists:
    list_of_values.append([dct['text'] for dct in lst])

print(list_of_values)
# [[], ['analytics', 'datascience', 'restaurants', 'machinelearning', 'bigData', 'CRM'], ['python', 'datascience']]

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

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