2

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.

Sai Kumar
  • 665
  • 2
  • 9
  • 21

2 Answers2

8

Via iter and zip:

>>> it = iter(list1 + list2)
>>> dict(zip(it,it))
{1: 'a', 2: 'b', 3: 'c', 5: 'd', 6: 'e', 7: 'f'}
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • 1
    there is a *hacky* quality to this answer which some might not be so fond of. But i am +1! – Ma0 Aug 30 '18 at 11:49
  • 2
    I don't see the hack, it is similar to the 'grouper' recipe at https://docs.python.org/3/library/itertools.html – Moberg Aug 30 '18 at 11:50
  • @Ev.Kounis It's not hacky IMO, I actually saw core CPython developer Raymond Hettinger use this kind of `zip()` on an iterator https://code.activestate.com/recipes/577916-fast-minmax-function/?in=user-178123 – Chris_Rands Aug 30 '18 at 11:51
  • 1
    @SaiKumar `iter()` creates an iterator (read here if you're not familar: https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do). The iterator is consumed via `next()` calls (unlike say a list), thus `zip()` creates the correct pairs – Chris_Rands Aug 30 '18 at 11:57
  • 2
    it returns an iterable (here called `it`) that will yield an item each time you call `next(it)`. You can try this out: `a = iter([1, 2, 3])` `next(a)` `next(a)` `next(a)` `next(a)` – Moberg Aug 30 '18 at 11:58
2

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'}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218