Posts

Showing posts from October, 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?