1

This is my list

myList = ['Bob', '5-10', 170, 'Tom', '5-5', 145, 'Bill', '6-5', '215']

I want to make into a dictionary like this.

{'Bob': ['5-10', 170], 'Bill': ['6-5', '215'], 'Tom': ['5-5', 145]}

I came up with this but it is very ugly and doesn't scale up.

def MakeDict():
    d = {}
    for x, i  in zip(myList, range(len(myList))):
       if i in (0, 3, 6):
           name = x
       elif i in (1, 4, 7):
           hieght = x
       elif i in (2, 5, 8):
           wieght = x
          d[name] = [hieght, wieght]
return d

What can I do?

user2333196
  • 5,406
  • 7
  • 31
  • 35

2 Answers2

5
  • Convert your list to an iterator
  • Now loop over it to get the keys.
  • For values during each iteration call itertools.islice on the iterator. Then call list() on the slice object to get a list.

>>> from itertools import islice
>>> myList = ['Bob', '5-10', 170, 'Tom', '5-5', 145, 'Bill', '6-5', '215']
>>> it = iter(myList)
>>> {key: list(islice(it, 2)) for key in it}
{'Bob': ['5-10', 170], 'Bill': ['6-5', '215'], 'Tom': ['5-5', 145]}

If you don't want to import anything use zip(*[iterator]*n) magic:

>>> {key: [height, weight]  for key, height, weight in zip(*[iter(myList)]*3)}
{'Bob': ['5-10', 170], 'Bill': ['6-5', '215'], 'Tom': ['5-5', 145]}
Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

I would use itertools.

Here is pushing you in the right direction:

from itertools import islice

See the examples at itertools.islice

waldens
  • 121
  • 1
  • 5