2

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        
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Anurag
  • 1,013
  • 11
  • 30

4 Answers4

11

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

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
4
>>> mylist = ["a",1,"b",2,"c",3]
>>> zippedlist = zip(mylist [0::2],mylist [1::2]) #slicing magic
>>> zippedlist
[('a', 1), ('b', 2), ('c', 3)]
>>> dictedlist = dict(zippedlist)
>>> dictedlist 
{'a': 1, 'c': 3, 'b': 2}

This works because of slicing [start:stop:skip]

list starting at 0, skipping 2

zipped with

list starting at 1, skipping 2

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
TehTris
  • 3,139
  • 1
  • 21
  • 33
1

To get all the keys from the list you can do:

keys = mylist[::2]

where the mylist[::2] creates a new list by iterating over every second element in mylist starting at index 0.

To get all the values from the list you can do:

vals = mylist[1::2]

where the mylist[1::2] creates a new list by iterating over every second element in mylist starting at index 1.

and then you can just use dict and zip:

dict(zip(keys,vals))  # or all in one line
dict(zip(mylist[::2], mylist[1::2]))

zip takes two lists like ["a","b","c"] and [1,2,3] and "zips" them together to give a list like

[("a",1), ("b", 2), ("c", 3)]

and dict takes an iterable of pairs and turns them into a dictionary.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
randlet
  • 3,628
  • 1
  • 17
  • 21
0

Using Compress and Cycle:-

from itertools import compress
from itertools import cycle

def fun(mylist):
    keys = compress(mylist,cycle([1,0]))
    values = compress(mylist,cycle([0,1]))
    mymap = dict(zip(keys,values))
    return mymap

mylist = ["a",1,"b",2,"c",3]

fun(mylist)
{'a': 1, 'c': 3, 'b': 2}
Anurag
  • 1,013
  • 11
  • 30