简体   繁体   中英

How to combine two lists into a dictionary in Python?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM