Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list to map in python

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        
like image 216
Anurag Avatar asked Dec 30 '25 17:12

Anurag


1 Answers

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

like image 163
Ashwini Chaudhary Avatar answered Jan 01 '26 07:01

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!