【问题标题】:How to reference and return values in a list of dictionaries如何在字典列表中引用和返回值
【发布时间】:2017-10-29 18:11:35
【问题描述】:

我有一个列表。

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

这是一个精简列表,其中包含三个示例行:

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 个字典的列表。

我需要从包含“文本”:“SOME_STRING”的键:值对中提取值。

另外,重要的是,每个值都应该返回一个与原始输入列表具有相同索引的列表中。换句话说,例如,对于 6 个 key:value 对的第二个列表,所有 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)

【问题讨论】:

    标签: python json list dictionary


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 2021-01-31
      • 2013-06-09
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多