Let us take a look at how to print a Python Dictionary (dict) line by line.
Example:
Let's take an example of a dictionary of countries and its famous city!
locations = {
'Tuvalu': 'Funafuti',
'Comoros': 'Moroni',
'Lesotho': 'Maseru',
'Liechtenstein': 'Vaduz',
'San Marino': 'San Marino',
'Andorra': 'Andorra la Vella',
'Bhutan': 'Thimphu',
'Seychelles': 'Victoria',
'Grenada': 'St. George\'s',
'Maldives': 'Male',
'Malta': 'Valletta',
'São Tomé and Príncipe': 'São Tomé',
'Vanuatu': 'Port Vila',
'Antigua and Barbuda': 'St. John\'s',
'Timor-Leste': 'Dili',
'Dominica': 'Roseau'
}
All we need to do is to iterates over the locations dictionary using the items() method which returns key-value pairs from the dictionary.
for country, city in locations.items():
print(country, "-", city)
We have made use of hyphen (-) as a seperator.
Output:Tuvalu - Funafuti,
Comoros - Moroni,
Lesotho - Maseru,
Liechtenstein - Vaduz,
San Marino - San Marino,
Andorra - Andorra la Vella,
Bhutan - Thimphu,
Seychelles - Victoria,
Grenada - St. George's,
Maldives - Male,
Malta - Valletta,
São Tomé and Príncipe - São Tomé,
Vanuatu - Port Vila,
Antigua and Barbuda - St. John's,
Timor-Leste - Dili,
Dominica - Roseau,
Read Documentation:
https://docs.python.org/3/library/stdtypes.html#dict.items
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!