153k views
1 vote
Write a loop that prints each country's population in country_pop. Sample output with input:

United States has 318463000 people.
India: 1247220000
Indonesia: 252164800
China: 1365830000
1. country_pop = {
2. 'China': 1365830000
3. 'India': 1247220000
4. 'United States': 318463000
5. 'Indonesia': 252164800
6. } # country populations as of 2014
7
8. print(country, 'has', pop, 'people.')

User AlexZd
by
5.3k points

1 Answer

4 votes

Answer:

  1. country_pop = {
  2. 'China': 1365830000,
  3. 'India': 1247220000,
  4. 'United States': 318463000,
  5. 'Indonesia': 252164800
  6. }
  7. for key in country_pop:
  8. print(key + " has " + str(country_pop[key]) + " people")

Step-by-step explanation:

The solution code is written in Python 3.

Given a dictionary, country_pop with data that includes four country along with their respective population (Line 1-6). We can use for in loop structure to traverse through each of the key (country) in the dictionary and print their respective population value (Line 7-8). The general loop structure through is as follow:

for key in dict:

do something

One key will be addressed for each round of loop and we can use that key to extract the corresponding value of the key (e.g. country_pop[key]) and print it out.

User Baraa
by
5.9k points