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?

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
guy4261 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.
guy4261 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)
Unknown said…
>>>list1 = ["a: b", "c: d", "e: f"]
Now how can I convert this list into dictionary
My expected output is:
{"a" : "b", "c" : "d", "e" : "f"}

Can anyone help me out???
guy4261 said…
list1 = ["a: b", "c: d", "e: f"]

d = {}
for item in list1:
k,v = item.split(":")
k = k.strip(" ")
v = v.strip(" ")
d[k] = v

assert d == {"a" : "b", "c" : "d", "e" : "f"}
dkwhyte said…
hey need some help in a similar but different situation. i would like the dictionary to give me the number of unique words in my list.
e.g l = [1,1,1,1,2,2,2,2,3,4,5,5]
and my dictionary will output
numbers in the dictionary :5

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code