0

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.

Calvin Ellington
  • 713
  • 3
  • 11
  • 21
  • 2
    dictionary keys have to be immutable! so no, you can not have a list as a key, but as a value, sure why not. – gold_cy Jul 10 '17 at 18:59
  • 2
    Adding to @aws_apprentice's point, though you can not have list as the key, you may type-cast it to tuple and make it as a key to your `dict` object – Moinuddin Quadri Jul 10 '17 at 19:01
  • 1
    Yes it is - use a tuple: `('Earth', 'Northern Hemisphere', 'North America', 'The United States of America')` instead of a list. – zwer Jul 10 '17 at 19:02
  • Thanks for your help everyone, how would I go about representing this entry as a tuple instead of a list? – Calvin Ellington Jul 10 '17 at 19:03
  • 2
    @NoOrangeJuice : [My Google](https://www.google.com/search?q=python+convert+list+to+tuple) gave me so many suggestions :) – Moinuddin Quadri Jul 10 '17 at 19:04
  • 1
    a = tuple(["my","list","of","things"]) ... or a = ("my","list","of","things") ... So either use parens to define a tuple instead of using [] to make a list, or convert the list to a tuple using tuple() – joeking Jul 10 '17 at 19:04
  • @Moinuddin Quadri Hahaha thank you – Calvin Ellington Jul 10 '17 at 19:05
  • seems like you should consider using a tree data structure where capitals are the nodes instead of this lists of lists structure. – Doug Coburn Jul 10 '17 at 19:07

1 Answers1

1

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

Eric Ed Lohmar
  • 1,832
  • 1
  • 17
  • 26
  • This is exactly what I was looking to do, both answers work for me. Specifically I'm very interested in working with `nested_dict` as that is new to me. Thanks for your help. – Calvin Ellington Jul 10 '17 at 21:21