-2
gender_freq = {}

for row in moma:
    gender = row[5]
    if gender not in gender_freq:
        gender_freq[gender] = 1
    else:
        gender_freq[gender] += 1

for gender, num in gender_freq.items():
    template = "There are {n:,} artworks by {g} artists"
    print(template.format(g=gender, n=num)) 

Why need .items() in for loop? I don't know what is .items() function and I can't understand why need it.

Joseph Park
  • 53
  • 1
  • 4
  • 1
    What error message are you getting? – Haukland Mar 03 '21 at 08:34
  • 6
    gender_freq is a dict, `items` gives you both keys and values, without `items` it will give only keys. – Raymond Reddington Mar 03 '21 at 08:35
  • 1
    if you want to iterate over values you ca use .values() – Belhadjer Samir Mar 03 '21 at 08:36
  • Does this answer your question? [How do I print the key-value pairs of a dictionary in python](https://stackoverflow.com/questions/26660654/how-do-i-print-the-key-value-pairs-of-a-dictionary-in-python) – Gino Mempin Mar 03 '21 at 09:40
  • I recommend using the Python docs as reference. The [Dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) section explains `.items` as part of [Looping Techniques](https://docs.python.org/3/tutorial/datastructures.html#looping-techniques). – Gino Mempin Mar 03 '21 at 09:49

2 Answers2

2

.items() returns a list with tuples corresponding to (key, value) pair in the dictionary.

this is your little example:

example = {
    'female': 8, 
    'male': 4
}

example.items() is

[('female', 8), ('male', 4)]

and when you do:

for gender, num in example.items():

gender will take these values: female, male

and num will take these values: 8, 4

when using items() you are iterating through the items of the dictionary in parallel.

alexzander
  • 1,586
  • 1
  • 9
  • 21
1

items() allows you to fetch the key/value pair of the dict in your for loop, this will avoid you looping on keys and asking for the value each time like so:

for gender in gender_freq:
    print(template.format(g=gender, n=gender_freq[gender]))

One more thing though, use the defaultdict this will allow you to avoid the check for the key each time you want to populate your dict:

from collections import defaultdict

gender_freq = defaultdict(int)

for row in moma:
    gender = row[5]
    gender_freq[gender] += 1
rafaelSorel
  • 41
  • 1
  • 6