Home > other >  How to merge 3 lists into a dictionary in Python
How to merge 3 lists into a dictionary in Python

Time:04-23

origen=['Philadelphia', 'New Orleans']
destino=['Atlanta', 'Dallas', 'Columbus', 'Boston']
costo=[ ['2','6','6','2'] , ['1','2','5','7'] ]

How I need them to be merged:

costo_envios={
              Philadelphia:{
                          Atlanta:2
                          Dallas:6
                          Columbus:6
                          Boston:2
                           }
              New Orleans:{
                           Atlanta:1
                           Dallas:2
                           Columbus:5
                           Boston:7             
                           }
             }

I thought of using maybe 2 nested 'for', but I get an "unlashable" error, which means I'm using the wrong type of index.

I also have tried this:

costo_envio={origen[l]:{destino[m]:costo[n]} for l,m,n in range(len(origen))}

But i got this error:

TypeError: cannot unpack non-iterable int object

I'm really new to Python, just started on my own this month. How can I do it?

CodePudding user response:

welcome!

You can use 2 for loops, the outer one to iterate over the origins and the lists of costs, and the inner one to iterate over the destinations and the costs.

Here's my code, hope it helps!

origen = ['Philadelphia', 'New Orleans']
destino = ['Atlanta', 'Dallas', 'Columbus', 'Boston']
costo = [['2', '6', '6', '2'], ['1', '2', '5', '7']]

my_dict = {}

for origin, cost_list in zip(origen, costo):
    my_dict[origin] = {}
    for dest, cost in zip(destino, cost_list):
        my_dict[origin][dest] = cost

Good luck!

CodePudding user response:

Create a dictionary of dictionaries. The first dictionary has keys that are the elements in the list 'origen'. The second dictionary has keys that are the elements in the list 'destino'. The values in the second dictionary are the corresponding values in the list 'costo'.

 costo_envios = {}
    for o, cs in zip(origen, costo):
        costo_envios[o] = {}
        for d, c in zip(destino, cs):
            costo_envios[o][d] = c
    costo_envios

CodePudding user response:

Define your desired structure and let Python dictionary comprehension work.

res = {o: {d:c for d, c in zip(destino, co)} for o, co in zip(origen, costo)}

You can also build 2 nested for loops if you think it is easier to read.

CodePudding user response:

You may take a look at the Python documentation and start studying about loops and the dict literal syntax.

Here is one implementation, that uses the concept of comprehensions and the zip function:

costo_envio = {o: {d: int(c) for d, c in zip(destino, co)} for o, co in zip(origen, costo)}

# {'Philadelphia': {'Atlanta': 2, 'Dallas': 6, 'Columbus': 6, 'Boston': 2},
#  'New Orleans': {'Atlanta': 1, 'Dallas': 2, 'Columbus': 5, 'Boston': 7}}
  • Related