How can I combine two lists into a dictionary in Python?
For example:
a_list = ['h1','a'],['h2' ,'a2']
b_list = ['hi', 'hello']
My output should be:
output = {'hi' : 'h1','a', 'hello' : 'h2','a2'}
How can I combine two lists into a dictionary in Python?
For example:
a_list = ['h1','a'],['h2' ,'a2']
b_list = ['hi', 'hello']
My output should be:
output = {'hi' : 'h1','a', 'hello' : 'h2','a2'}
In the example that you have given, you have used one list as the keys to your dictionary, and the other list as the values for your dictionary.
If this is what you want, then you can combine the list into key,value pairs using zip
as follows:
a_list = ['h1','a'],['h2' ,'a2']
b_list = ['hi', 'hello']
d = {}
for k,v in zip(b_list,a_list):
d[k] = v
print(d)
The result:
{'hi': ['h1', 'a'], 'hello': ['h2', 'a2']}
As a side note, in the example you gave, a_list
is actually a tuple
of lists
.
It will also work as a list
of lists
:
a_list = [['h1','a'],['h2' ,'a2']]
One way of solving this is using dictionary comprehension.
>>> a_list = ['h1','a'],['h2' ,'a2']
>>> b_list = ['hi', 'hello']
>>> {x:y for x,y in zip(b_list,a_list)}
Output:
{'hi': ['h1', 'a'], 'hello': ['h2', 'a2']}