【问题标题】:Parsing values from a list of dictionaries with nested list in Python在Python中使用嵌套列表解析字典列表中的值
【发布时间】:2017-02-08 00:19:41
【问题描述】:

我有一个包含这种格式信息的字典列表:

p_mat_list = [
    {'name': 'Mirror', 'link': '/somelink1/'},
    {'name': 'Gold Leaf', 'link': '/somelink2/'}
]

首先,创建包含所有名称值的 python 列表:

product_materials = []
for material in p_mat_list:
    product_materials.append(material['name'])

但是,当列表具有嵌套列表和字典时,我不知道获取所有名称值的最佳方法是什么,如下所示:

p_mat_list = [
    [{'name': 'Painted'}, {'name': 'Wood'}],
    {'name': 'Mirror'},
    {'name': 'Gold Leaf'}
]

如何获取所有这些名称值:PaintedWoodMirrorGold Leaf

另外,我如何将每个嵌套列表中的所有字典中的名称值合并为一个值,然后将其与其他值一起放入列表中,这样会得到这样的值:Painted Wood、Mirror、Gold Leaf。

不会有嵌套更多级别的列表,并且其中不会有两个以上的字典,例如从下面的这个列表中需要得到这样的值: 彩绘木头、镜子、涂漆木头、金箔。

p_mat_list = [
[{'name': 'Painted'}, {'name': 'Wood'}],
{'name': 'Mirror'},
[{'name': 'Varnished'}, {'name': 'Wood'}],
{'name': 'Gold Leaf'}
]

【问题讨论】:

  • 我刚刚注意到的一点:上一个示例的结果是否真的应该将'Painted Wood' 包含为单个字符串,而不是'Painted''Wood' 作为单独的字符串?如果是这样,这与您的第一个示例不一致,在这种情况下,我认为我们需要进一步澄清您的意思。

标签: python list dictionary


【解决方案1】:

如果您愿意引入外部库,您可以使用来自more-itertoolscollapse() function。像这样使用它:

import more_itertools as mt
list(mt.collapse(p_mat_list, base_type=dict))
    [{'name': 'Painted'},
     {'name': 'Wood'},
     {'name': 'Mirror'},
     {'name': 'Gold Leaf'}]

那么在您的情况下,您可以从每个字典中提取与 'name' 对应的值,而不是列出它们。

>>> [d['name'] for d in mt.collapse(p_mat_list, base_type=dict)]

这样做的好处是您不必担心列表嵌套有多少级。

【讨论】:

    【解决方案2】:

    最好的方法是展平你有这样一个函数的复杂列表:

    def flatten(x):
        if isinstance(x, dict) :
            return [x]
        elif isinstance(x, collections.Iterable) :
            return [a for i in x for a in flatten(i)]
        else:
            return [x]
    

    此函数将您的p_mat_list 作为参数并返回一个字典列表。

    get_list = flatten(p_mat_list)
    
    product_materials = []
    for material in get_list :
        product_materials.append(material['name'])
    

    您的product_materials 列表:

    ['Painted', 'Wood', 'Mirror', 'Gold Leaf']
    

    【讨论】:

    • 请注意,有些人认为将 lambda 绑定到名称是一种反模式。这些消息来源声称,在这些情况下,应该定义一个成熟的命名函数。
    • "Some" 是官方 Python 风格指南。
    • @AndrasDeak 现在怎么样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2017-06-17
    • 2013-11-15
    相关资源
    最近更新 更多