Looping over a dictionary

Hi I wrote my code like this:

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

for freq, gender in gender_freq.items():
   output = "There are {gen:,} artworks by {num} artists".format(num = freq, gen= gender)
   print(output)

Why does the variable gen returns the frequency and num return the gender? Is there any rule to this please help?

Hi minhha!

Try this instead:
for gender, freq in gender_freq.items():

a dictionary looks like this:
key : value --> gender : frequency
You assign the gender as the key to the dictionary and increase each occurence by one which makes it the value (frequency)

hope that was not too confusing…
br
Marina

1 Like

You need to do it like this:

for gender, freq in gender_freq.items():
   output = "There are {gen} artworks by {num:,} artists".format(num=freq, gen=gender)
   print(output)

But the resulting sentence is a bit weird.

There are Male artworks by 13,492 artists
There are Gender Unknown/Other artworks by 794 artists
There are Female artworks by 2,443 artists

1 Like

thank you, it what I needs. Its not confusing at all!