I have two lists
list1 = [1,a,2,b,3,c]
list2 = [5,d,6,e,7,f]
I tried to use list(zip(list1, list2))
Then is what I got:
[(1, 5), ('a', 'd'), (2, 6), ('b', 'e'), (3, 7), ('c', 'f')]
I want something like this to be my output:
{1:a, 5:d, 2:b, 6:e, 3:c,7:f}
Any help is appreciated.
Via iter
and zip
:
>>> it = iter(list1 + list2)
>>> dict(zip(it,it))
{1: 'a', 2: 'b', 3: 'c', 5: 'd', 6: 'e', 7: 'f'}
I'd first add your two lists together
>>> values = list1 + list2
>>> values
[1, 'a', 2, 'b', 3, 'c', 5, 'd', 6, 'e', 7, 'f']
Then use a dict
comprehension to stride through the list by every other element, and zip that against the same stride but offset by one.
>>> {key:value for key,value in zip(values[::2], values[1::2])}
{1: 'a', 2: 'b', 3: 'c', 5: 'd', 6: 'e', 7: 'f'}
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.