I have a list and I want to convert this list into map
mylist = ["a",1,"b",2,"c",3]
mylist is equivalent to
mylist = [Key,Value,Key,Value,Key,Value]
So Input:
mylist = ["a",1,"b",2,"c",3]
Output:
mymap = {"a":1,"b":2,"c":3}
P.S: I already have written following function that do same work, but I want to use iterator tools of python:
def fun():
mylist = ["a",1,"b",2,"c",3]
mymap={}
count = 0
for value in mylist:
if not count%2:
mymap[value] = mylist[count+1]
count = count+1
return mymap
Using iter and dict-comprehension:
>>> mylist = ["a",1,"b",2,"c",3]
>>> it = iter(mylist)
>>> {k: next(it) for k in it}
{'a': 1, 'c': 3, 'b': 2}
Using zip and iter:
>>> dict(zip(*[iter(mylist)]*2)) #use `itertools.izip` if the list is huge.
{'a': 1, 'c': 3, 'b': 2}
Related: How does zip(*[iter(s)]*n) work in Python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With