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!
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.
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.
These are things like integers, floats, strings, Booleans, functions. Even tuples can be a key. A dictionary or a list cannot be a key.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With