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

时间:2017-10-29 18:11:36

标签: python json list dictionary

我有一份清单。

每个列表中都有几千个字典列表。一个列表可能包含多个词典,一个词典,或者它可能是空的。

这是一个简略列表,列表中有三个示例行:

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]}]

因此,在此列表中有一个空列表,一个列表包含6个词典,一个列表包含2个词典。

我需要从key:value对中提取值,其中包括' text':' SOME_STRING'。

此外,重要的是,每个值都应返回到原始输入列表中具有相同索引的列表中。换句话说,例如,对于6个键:值对的第二个列表,所有6个值应该在列表中以与原始list_of_lists中相同的索引返回

所以这是我上面例子中我想要的输出:

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

我已经编写了下面的代码,几乎可以满足我的需求。它返回所有这些字符串的列表,但它不会在同一索引处返回它们,并且它还返回我不想要的索引字典。

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)

1 个答案:

答案 0 :(得分:1)

为每个嵌套的dicts列表创建一个不同的列表,并附加到父列表。空列表获得零迭代,因此结果列表保持为空,而其他列表的值在列表理解中收集:

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']]