-6

Suppose I have a list of

L = ['hello', 'hello', 'hi', 'hello', 'hello']

I want to count how many 'hello' and 'hi' in the list. So that the result is 'hello': 4, 'hi': 1.

How would I implement this result in dictionary form? My professor hasn't gone over this yet, so I'm not sure how to convert from list to dictionary.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Ramon Hallan
  • 125
  • 12

2 Answers2

1

Use a counter:

>>> from collections import Counter
>>> def how_many(li): return Counter(li)
... 
>>> how_many(['hello', 'hello', 'hi', 'hello', 'hello'])
Counter({'hello': 4, 'hi': 1})

Or, you can do:

>>> li=['hello', 'hello', 'hi', 'hello', 'hello']
>>> {e:li.count(e) for e in set(li)}
{'hi': 1, 'hello': 4}

Or, you can do:

>>> di={}
>>> for e in li:
...    di[e]=di.get(e, 0)+1
... 
>>> di
{'hi': 1, 'hello': 4}
dawg
  • 98,345
  • 23
  • 131
  • 206
0

Using no external modules and only the count, although there would be some redundancy using dict comprehension:

d = {itm:L.count(itm) for itm in set(L)}

If you are allowed to use external modules and do not need to implement everything on your own, you could use Python's defaultdict which is delivered through the collections module:

#!/usr/bin/env python3
# coding: utf-8

from collections import defaultdict

word_list = ['hello', 'hello', 'hi', 'hello', 'hello']

d = defaultdict(int)
for word in word_list:
    d[word] += 1

print(d.items())

Giving you:

dict_items([('hi', 1), ('hello', 4)])

EDIT: As stated in the comments you could use a Counter like this, which would be easier:

#!/usr/bin/env python3
# coding: utf-8

from collections import Counter

word_list = ['hello', 'hello', 'hi', 'hello', 'hello']

c = Counter(word_list)

print(c)

Giving you:

Counter({'hello': 4, 'hi': 1})
albert
  • 8,027
  • 10
  • 48
  • 84
  • [`collections.Counter()`](https://docs.python.org/3.5/library/collections.html#collections.Counter) – Remi Guan Nov 25 '15 at 01:36
  • I don't understand the downvote, its not a bad answer, just a different answer – user2682863 Nov 25 '15 at 01:40
  • Your first answer was exactly what I'm looking for. Thanks! – Ramon Hallan Nov 25 '15 at 01:57
  • 1
    -1: `{itm:L.count(itm) for itm in L}` simply erases the dict key with the updated count until the final unique list value of duplicates. Wasteful and slow. You should do `{itm:L.count(itm) for itm in set(L)}` so that the count step is only done once per unique entry in the list. – the wolf Nov 30 '15 at 22:41
  • @thewolf: This was not part of my answer, but added by David Zemens. I updated my answer due to your comment. Thanks for this improvement. – albert Dec 01 '15 at 00:12