0

I saw this code written in an online course, and am confused why did python exactly returned 'France' 'Spain' 'Russia', and 'Japan'. I mean the country isn't actually defined as the 'key' of the given 'key value pairs'... right? Or is that how it really is defined?

capitals = {
    "France": "Paris",
    "Spain": "Madrid",
    "Russia": "Moscow",
    "Japan": "Tokyo",
}

for country in capitals:
    print(country)

Prints:

France
Spain
Russia
Japan
martineau
  • 119,623
  • 25
  • 170
  • 301
  • A for loop on a dictionary returns keys – ᴀʀᴍᴀɴ Oct 28 '21 at 12:52
  • This is the structure of a dictionary, ```d_name = {: }```. – sophocles Oct 28 '21 at 12:53
  • 1
    Does this answer your question? [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – MatBBastos Oct 28 '21 at 12:54
  • Yes the country names are the keys of the `capitals` [dictionary](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict). Note that `country` is just a name being given to them in the `for` loop (see [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html)). Any other valid identifier, such as `nation`, would have worked just as well. – martineau Oct 28 '21 at 13:57

2 Answers2

1

am confused why did python exactly returned 'France' 'Spain' 'Russia', and 'Japan'.

Iterating over a dictionary (for country in capitals:) iterates over its keys.

(The variable name country there could just as well be wibblewobble; Python doesn't care. (You should name it sensibly, though. Not wibblewobble.))

I mean the country isn't actually defined as the 'key' of the given 'key value pairs'... right?? or is that how it really is defined?!

For that dictionary, that's exactly how it is. The pairs are country (key) -> capital (value).

If you want to see each country and its capital, you'd use dict.items():

for country, capital_city in capitals.items():
    print(country, capital_city)
AKX
  • 152,115
  • 15
  • 115
  • 172
0

capitals is a dictionary - the countries are the keys and the capitals are the values. Iterating over the dictionary returns all keys.

Bashton
  • 339
  • 1
  • 11