Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of keys and list of values to a dictionary

I have these lists:

list1 = ["a","b","c"]
list2 = ["1","2","3"]

I need to add them to a dictionary, where list1 is the key and list2 is the value.

I wrote this code:

d = {}
for i in list1:
    for j in list2:
        d[i] = j
print d

The output is this:

{'a':'3','b':'3','c':'3'}

What's wrong with this code? How can I write it so the output is

{'a':'1','b':'2','c':'3'}

Thanks!

like image 339
Aei Avatar asked Nov 05 '12 04:11

Aei


People also ask

How do you change a list into a dictionary?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

How do you convert a list to a key value pair in Python?

By using enumerate() , we can convert a list into a dictionary with index as key and list item as the value. enumerate() will return an enumerate object. We can convert to dict using the dict() constructor.

Can a list be a key in a dictionary Python?

These are things like integers, floats, strings, Booleans, functions. Even tuples can be a key. A dictionary or a list cannot be a key.

Can you put a list as a value in a dictionary Python?

It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.


1 Answers

Zip the lists and use a dict comprehension :

{i: j for i, j in zip(a, b)}

Or, even easier, just use dict() :

dict(zip(a, b))

You should keep it simple, so the last solution is the best, but I kept the dict comprehension example to show how it could be done.

like image 173
Vincent Savard Avatar answered Sep 27 '22 20:09

Vincent Savard