简体   繁体   中英

How to merge two lists by index

I have two lists:

i = ['a', 'b', 'c']
x = [1,2,3]

i need to produce such dictionary:

xxx = { 'a': [a, 1],
'b': [b, 2],
'c': [c, 3]}

I have done this:

for indx in i:
    for indx2 in x:
        xxx.update({indx: [indx, indx2]})

but obvioulsy it doesnt work

Using dict comprehension:

>>> i = ['a', 'b', 'c']
>>> x = [1,2,3]
>>> {key: [key, value] for key, value in zip(i, x)}
{'a': ['a', 1], 'c': ['c', 3], 'b': ['b', 2]}

how about this, if tuple can be the value of your dict.

i= ['a', 'b', 'c']

x= [1, 2, 3]

dict(zip(i,zip(i,x)))
 {'a': ('a', 1), 'b': ('b', 2), 'c': ('c', 3)}

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