【问题标题】:How to extract specific value from list of list of dictionary?如何从字典列表中提取特定值?
【发布时间】:2020-11-10 21:45:12
【问题描述】:

我正在尝试提取“Alt_name”的值并需要将其存储为列表。

输入:

[
 [{'Name': 'Selin', 'Age': '31', 'Active': 'true', 'Items': '4', 'Alt_name': 'selin-hub', 'type': 'Normal', 'Colour':'Blue'}],
 [{'Name': 'Jenny', 'Age': '21', 'Active': 'true', 'Items': '2', 'Alt_name': 'jenny-cean', 'type': 'Normal', 'Colour': 'green'}],
 [{'Name': 'Vuly', 'Age': '20', 'Active': 'true', 'Items': '3', 'Alt_name': 'clary', 'type': 'Normal'}] 
]

预期输出:

 ['selin-hub','jenny-cean','clary']

如何从上述输入中提取 Alt_name 的值?

提前致谢。

【问题讨论】:

    标签: python-3.x list dictionary types


    【解决方案1】:

    您有一个列表列表,每个列表都包含一个字典。因此,只需浏览列表,选择第一个元素(字典),然后选择 'Alt_name' 字段。

    将您的列表设置为变量l,您可以使用List Comprehension 找到所需的输出:

    [d[0]['Alt_name'] for d in l]
    

    如果您可以修改此列表,您可以考虑将其设为字典列表,即:

    l = [
        {'Name': 'Selin', 'Age': '31', 'Active': 'true', 'Items': '4', 'Alt_name': 'selin-hub', 'type': 'Normal', 'Colour':'Blue'},
        {'Name': 'Jenny', 'Age': '21', 'Active': 'true', 'Items': '2', 'Alt_name': 'jenny-cean', 'type': 'Normal', 'Colour': 'green'},
        {'Name': 'Vuly', 'Age': '20', 'Active': 'true', 'Items': '3', 'Alt_name': 'clary', 'type': 'Normal'}
    ]
    

    在这种情况下,您可以通过编写获得所需的输出

    [d['Alt_name'] for d in l]
    

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多