Python 如何在字典列表中引用和返回值
我有一份清单 在每个列表中都有几千个字典列表。一个列表可能包含多个词典、一个词典,或者可能为空 下面是一个简短列表,列表中有三行示例:Python 如何在字典列表中引用和返回值,python,json,list,dictionary,Python,Json,List,Dictionary,我有一份清单 在每个列表中都有几千个字典列表。一个列表可能包含多个词典、一个词典,或者可能为空 下面是一个简短列表,列表中有三行示例: list_of_lists = [[], [{'text': 'analytics', 'indices': [18, 28]}, {'text': 'datascience', 'indices': [35, 47]}, {'text': 'restaurants', 'indices': [54, 66]}, {'text': 'machinelearnin
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个字典的列表
我需要从包含“text”:“SOME_STRING”的key:value对中提取值
同样重要的是,每个值都应该返回到一个列表中,该列表中的索引与原始输入列表中的索引相同。换句话说,例如,对于第二个包含6个键:值对的列表,所有6个值都应该在一个列表中返回,该列表的索引与它在原始列表中的索引相同
下面是我从上述示例中得到的期望输出:
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)
为每个嵌套的DICT列表创建不同的列表,并附加到父列表。空列表的迭代次数为零,因此生成的列表保持为空,而其他列表的值在列表中收集:
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']]