Saturday, October 29, 2011

Pythonic way to convert a list into dictionary

Here is a simple Python code that converts a list into a dictionary.

 def list_to_dict(li):  
     dct = {}  
     for item in li:  
         if dct.has_key(item):  
             dct[item] = dct[item] + 1  
         else:  
             dct[item] = 1  
     return dct  

 li = [1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7, 7]  
 print list_to_dict(li)  

Now I am looking for more Pythonic way to do this task. Any ideas?

9 comments:

Will said...

Try this:

dict([i, li.count(i)] for i in li)

CC said...

for ver 2.4 onward this should work

>>> l = [1,1,1,1,2,2,2,3,3,4]
>>> from collections import Counter
>>> f = Counter(l)
>>> f
Counter({1: 4, 2: 3, 3: 2, 4: 1})

jim said...

I dont know if using default dict is something you would like:

from collections import defaultdict
dct=defaultdict(int)
for i in li: dct[i]+=1

but this is certainly an antidiom:
if dct.has_key(item) #no no
if item in dct #YES

CC said...

Typo there, I meant version 2.7

Andreas said...

There is a nice thread on stackoverflow on this

Andreas

Tamim Shahriar (Subeen) said...

Thanks everyone.

Amit Pathak said...

dict(zip(li,li))

גיא said...

While the code samples here are very nice, what I think is the most meaningful technique not used here is to use dictionary's get(key,defaultVal) method.

def list_to_dict(li):
dct = {}
for item in li:
dct[item] = dct.get(item,0) + 1
return dct

li = [1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7, 7]
print list_to_dict(li)

You can use the get method cleaner.

גיא said...

Using dict's .get method:

def list_to_dict(li):
dct = {}
for item in li:
dct[item] = dct.get(item,0) + 1
return dct

li = [1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7, 7]
print list_to_dict(li)