-10

I have a list:

 X = ['raz', 'dwa', 'raz', 'trzy', 'dwa', 'raz', 'trzy', 'cztery']

and want Output:

{'cztery': 1, 'dwa': 2, 'raz': 3, 'trzy': 2}
Kevin
  • 74,910
  • 12
  • 133
  • 166

3 Answers3

4

You can use a dictionary comprehension:

>>> lst = ['raz', 'dwa', 'raz', 'trzy', 'dwa', 'raz', 'trzy', 'cztery']
>>> {x:lst.count(x) for x in set(lst)}
{'raz': 3, 'cztery': 1, 'dwa': 2, 'trzy': 2}
>>>

or, you can use collections.Counter:

>>> from collections import Counter
>>> Counter(lst)
Counter({'raz': 3, 'dwa': 2, 'trzy': 2, 'cztery': 1})
>>>

The second solution is probably what you want because it does the same thing as the comprehension, is more efficient, and also uses the Counter class, which comes with a lot of great tools (e.g. most_common and subtract).

  • @Downvoter - Please leave a reason you downvoted. I care a lot about the quality of my work. Hence, if you have found something wrong with my post, please let me know so I can address it. –  Oct 10 '13 at 20:32
1

Another method using stdlib:

In [6]: from collections import Counter
In [7]: l = ['raz', 'dwa', 'raz', 'trzy', 'dwa', 'raz', 'trzy', 'cztery']
In [8]: dict(Counter(l).items())
Out[8]: {'cztery': 1, 'dwa': 2, 'raz': 3, 'trzy': 2}
Demian Brecht
  • 21,135
  • 5
  • 42
  • 46
0

Just demonstrating the version with groupby that Brian suggested.

import itertools
data = ['raz', 'dwa', 'raz', 'trzy', 'dwa', 'raz', 'trzy', 'cztery']
print({k:len(list(v)) for k, v in itertools.groupby(sorted(data))})
Matthias
  • 12,873
  • 6
  • 42
  • 48