0

I'm a Python newbie and currently learning about dictionaries. I have the following exercise to make: Create a dict, country_counts, whose keys are country names, and whose values are the number of times the country occurs in the countries list.

the following is the code, which is working without a problem.

from countries import country_list # Note: the list is so large, 
                                   # and is extracted from another file


country_counts = {}

for country in country_list:
    if country not in country_counts:
        country_counts[country] = 1
    else:
        country_counts[country] = country_counts[country] + 1

I didn't understand how did the keys of country_list get inserted in country_count, with this for loop without assigning the keys? hope that makes sense. Thank you

Zein
  • 73
  • 6
  • The for loop *is* inserting the keys. Why do you think it isn't? – Daniel Roseman Feb 02 '18 at 17:40
  • technically, this would satisfy your brief: `from collections import Counter; Counter(country_list)` – jpp Feb 02 '18 at 17:43
  • 1
    When you do `country_counts[country] = 1`, what it essentially means is -- create a new key value pair in the dict with `country` as the key and `1` as the value. Try doing `print(country_counts)` to see if it makes it clear. Also, read up on Dictionaries in Python. – DM_Morpheus Feb 02 '18 at 17:49
  • You can also do it without the else using get with a default value of 0 – Veltzer Doron Feb 02 '18 at 17:53

0 Answers0