dict-count.py
· 682 B · Python
Orginalformat
# You need to write a loop that counts the occurrences of each word in a list.
#
# Consider, if you had a big str that was a text, like say: https://zcw.guru/kristofer/hamlet
#
# strive to be "pythonic" in your code expressions, okay?
colors = ["red", "green", "blue", "green", "red", "green"]
# Not Pythonic Code
d = {}
for color in colors:
if color not in d:
d[color] = 0
d[color] += 1
# Pythonic Code
d = {}
for color in colors:
d[color] = d.get(color, 0) + 1 # notice, no need for if
# Another Pythonic Code
from collections import defaultdict
d = defaultdict(int)
for color in colors:
d[color] += 1
# code output
# {'red': 2, 'green': 3, 'blue': 1}
1 | # You need to write a loop that counts the occurrences of each word in a list. |
2 | # |
3 | # Consider, if you had a big str that was a text, like say: https://zcw.guru/kristofer/hamlet |
4 | # |
5 | # strive to be "pythonic" in your code expressions, okay? |
6 | |
7 | colors = ["red", "green", "blue", "green", "red", "green"] |
8 | |
9 | # Not Pythonic Code |
10 | d = {} |
11 | for color in colors: |
12 | if color not in d: |
13 | d[color] = 0 |
14 | d[color] += 1 |
15 | |
16 | # Pythonic Code |
17 | d = {} |
18 | for color in colors: |
19 | d[color] = d.get(color, 0) + 1 # notice, no need for if |
20 | |
21 | # Another Pythonic Code |
22 | from collections import defaultdict |
23 | d = defaultdict(int) |
24 | for color in colors: |
25 | d[color] += 1 |
26 | |
27 | # code output |
28 | # {'red': 2, 'green': 3, 'blue': 1} |