Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to convert a list to dictionary

Tags:

python

I need help in the most efficient way to convert the following list into a dictionary:

l = ['A:1','B:2','C:3','D:4']  

At present, I do the following:

mydict = {}
for e in l:
    k,v = e.split(':')
    mydict[k] = v

However, I believe there should be a more efficient way to achieve the same. Any idea ?

like image 318
IUnknown Avatar asked May 04 '13 12:05

IUnknown


People also ask

Can you convert a list into a dictionary?

Converting a List to a Dictionary Using Enumerate() By using enumerate() , we can convert a list into a dictionary with index as key and list item as the value. enumerate() will return an enumerate object. We can convert to dict using the dict() constructor.

How do I convert a list to a dictionary in Python?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.

Is a dictionary more efficient than a list?

It is more efficient to use dictionaries for the lookup of elements as it is faster than a list and takes less time to traverse. Moreover, lists keep the order of the elements while dictionary does not. So, it is wise to use a list data structure when you are concerned with the order of the data elements.

Is dictionary more efficient than list Python?

A dictionary is 6.6 times faster than a list when we lookup in 100 items.


2 Answers

use dict() with a generator expression:

>>> lis=['A:1','B:2','C:3','D:4']
>>> dict(x.split(":") for x in lis)
{'A': '1', 'C': '3', 'B': '2', 'D': '4'}

Using dict-comprehension ( as suggested by @PaoloMoretti):

>>> {k:v for k,v in (e.split(':') for e in lis)}
{'A': '1', 'C': '3', 'B': '2', 'D': '4'}

Timing results for 10**6 items:

>>> from so import *
>>> %timeit case1()
1 loops, best of 3: 2.09 s per loop
>>> %timeit case2()
1 loops, best of 3: 2.03 s per loop
>>> %timeit case3()
1 loops, best of 3: 2.17 s per loop
>>> %timeit case4()
1 loops, best of 3: 2.39 s per loop
>>> %timeit case5()
1 loops, best of 3: 2.82 s per loop

so.py:

a = ["{0}:{0}".format(i**2) for i in xrange(10**6)]

def case1():
    dc = {}
    for i in a:
        q, w = i.split(':')
        dc[q]=w

def case2():
    dict(x.split(":") for x in a)


def case3():
    {k:v for k,v in (e.split(':') for e in a)}

def case4():
    dict([x.split(":") for x in a])

def case5():
    {x.split(":")[0] : x.split(":")[1] for x in a}
like image 200
Ashwini Chaudhary Avatar answered Oct 01 '22 06:10

Ashwini Chaudhary


>>> dict(map(lambda s: s.split(":"), ["A:1", "B:2", "C:3", "D:4"]))
{'A': '1', 'C': '3', 'B': '2', 'D': '4'}
like image 41
richselian Avatar answered Oct 01 '22 06:10

richselian