如何使用Python以有序的方式处理嵌套列表中的dicts

时间:2017-07-10 18:56:23

标签: python list python-3.x dictionary

为了说明我的困境,我将使用以下代码。

formatted_list = []
nested_list = [
        [
            ['Earth', 'Northern Hemisphere', 'North America', 'The United States of America'], 
            ['California', 'Kentucky', 'Colorado', 'Oregon'], 
            ['Sacramento', 'Frankfurt', 'Denver', 'Salem']
        ], 
        [
            ['Earth', 'Northern Hemisphere', 'North America', 'The United States of America'], 
            ['Florida', 'Kentucky', 'Nevada', 'Oregon'], 
            ['Tallahassee', 'Frankfurt', 'Carson City', 'Salem']
        ]
            ]

for values in nested_list:
    for global_attributes in values[0]:
        formatted_list.append(global_attributes)

for values in nested_list:
    formatted_list.append(dict(zip(values[1], values[2])))

print(formatted_list)

现在让我说我是一个外星侦察员,我正在尝试编写一个python程序,它会告诉我的母舰使用嵌套列表的州首府的位置。 ['Earth', 'Northern Hemisphere', 'North America', 'The United States of America']显然适用于所有州及其首都。然而,并非每个州都拥有相同的资本。我目前的代码提供了以下内容:

['Earth', 'Northern Hemisphere', 'North America', 'The United States of America', 'Earth', 'Northern Hemisphere', 'North America', 'The United States of America', {'California': 'Sacramento', 'Kentucky': 'Frankfurt', 'Colorado': 'Denver', 'Oregon': 'Salem'}, {'Florida': 'Tallahassee', 'Kentucky': 'Frankfurt', 'Nevada': 'Carson City', 'Oregon': 'Salem'}]

我创建了一个字典,将状态与各自的城市配对formatted_list。我的问题是:

  

如何告诉python关联['Earth', 'Northern Hemisphere', 'North America', 'The United States of America']条目   跟随它的整个字典?

因为可以将整个列表作为字典中的键或值吗?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

假设您的nested_list始终保持三个子列表保留[[Planet, Hemishpere, Continent, Country], [State/Province1, State/Province2, State/Province3, State/Province4], [Capital1, Capital2, Capital3, Capital4]]的结构。我们可以使用一种看起来很脏的嵌套try/except系统来构建一个树结构,其中每个区域大小都是一个节点。它看起来像这样:

nested_list = [
    [
        ['Earth', 'Northern Hemisphere', 'North America', 'The United States of America'],
        ['California', 'Kentucky', 'Colorado', 'Oregon'],
        ['Sacramento', 'Frankfurt', 'Denver', 'Salem']
    ],
    [
        ['Earth', 'Northern Hemisphere', 'North America', 'The United States of America'],
        ['Florida', 'Kentucky', 'Nevada', 'Oregon'],
        ['Tallahassee', 'Frankfurt', 'Carson City', 'Salem']
    ]
]

locations = {}

for sub_group in nested_list:
    planet = sub_group[0][0]
    hemisphere = sub_group[0][1]
    continent = sub_group[0][2]
    country = sub_group[0][3]

    for i in range(len(sub_group[1])):
        try:
            locations[planet][hemisphere][continent][country]{sub_group[1][i] = sub_group[2][i]

        except KeyError:
            try:
                locations[planet][hemisphere][continent][country] = {}

            except KeyError:
                try:
                    locations[planet][hemisphere][continent] = {}

                except KeyError:
                    try:
                        locations[planet][hemisphere] = {}

                    except KeyError:
                        locations[planet] = {}

print(locations)

注意:可能有一种方法可以使用this answer的嵌套默认值而不是嵌套的try/except

注意2:在发布之前可能应该做更多的研究,但有一个名为nested_dict的软件包看起来像是提供了一种自动生成的默认字典。该代码看起来像:

from nested_dict import nested_dict

nested_list = [
    [
        ['Earth', 'Northern Hemisphere', 'North America', 'The United States of America'],
        ['California', 'Kentucky', 'Colorado', 'Oregon'],
        ['Sacramento', 'Frankfurt', 'Denver', 'Salem']
    ],
    [
        ['Earth', 'Northern Hemisphere', 'North America', 'The United States of America'],
        ['Florida', 'Kentucky', 'Nevada', 'Oregon'],
        ['Tallahassee', 'Frankfurt', 'Carson City', 'Salem']
    ]
]

locations = nested_dict(4, dict)

for sub_group in nested_list:
    planet = sub_group[0][0]
    hemisphere = sub_group[0][1]
    continent = sub_group[0][2]
    country = sub_group[0][3]

    for i in range(len(sub_group[1])):
        locations[planet][hemisphere][continent][country][sub_group[1][i]] = sub_group[2][i]

print(locations.to_dict())

输出方式如下:{'Earth': {'Northern Hemisphere': {'North America': {'The United States of America': {'California': 'Sacramento', 'Kentucky': 'Frankfurt', 'Colorado': 'Denver', 'Oregon': 'Salem', 'Florida': 'Tallahassee', 'Nevada': 'Carson City'}}}}}