如何使用Python以有序方式处理嵌套列表中的字典 [英] How to process dicts within nested lists in an ordered manner with Python

查看:237
本文介绍了如何使用Python以有序方式处理嵌套列表中的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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']条目 紧随其后的整个字典?

是否有可能将整个列表作为字典中的键或值?感谢您的帮助.

解决方案

让我们假设您的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)

注意:根据此答案,有一种方法可以使用嵌套的defaultdict代替嵌套的try/except. /p>

注意2:发布前可能应该做更多的研究,但是有一个名为 nested_dict 看起来像它提供了一种自动生成的默认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'}}}}}

To illustrate my dilemma I'll use the following code.

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)

Now lets say I'm an alien scout and I'm trying to write a python program that will tell my mothership the location of state capitals using a nested list. ['Earth', 'Northern Hemisphere', 'North America', 'The United States of America'] obviously applies to all states and their capitals. However not every state has the same capital. My current code gives the following:

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

I've created a dictionary that pairs states with their respective cities withing formatted_list. My question is:

How can I tell python to associate the ['Earth', 'Northern Hemisphere', 'North America', 'The United States of America'] entry with the entire dictionary that follows it?

As in is it possible to have an entire list as a key or value within a dictionary? Thanks for your help.

解决方案

Let's assume your nested_list always maintains that structure where the three sublists keep the [[Planet, Hemishpere, Continent, Country], [State/Province1, State/Province2, State/Province3, State/Province4], [Capital1, Capital2, Capital3, Capital4]]. We can use a kind of dirty looking nested try/except system to build a tree structure where each region size is a node. It looks like this:

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)

Note: There may be a way of using nested defaultdicts per this answer instead of the nested try/except.

Note 2: Probably should have done a little more research before posting, but there is a package called nested_dict that looks like it offers a sort of auto-generated default dict. That code would look like:

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())

Either way the output looks like: {'Earth': {'Northern Hemisphere': {'North America': {'The United States of America': {'California': 'Sacramento', 'Kentucky': 'Frankfurt', 'Colorado': 'Denver', 'Oregon': 'Salem', 'Florida': 'Tallahassee', 'Nevada': 'Carson City'}}}}}

这篇关于如何使用Python以有序方式处理嵌套列表中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆