Prev: Constructing dictionaries | Next: Dictionary vs. List
The key:value pairs of the dictionary are of the form:
{Code: [CountryName, Capital, Population]}
We use pprint.pprint() method to print the dictionary in a more readable format
import pprint
country = {}
country['GR'] = ['Greece', 'Athens', 11]
country['IT'] = ['Italia', 'Rome', 61]
country['ES'] = ['Spain', 'Madrid', 46]
pprint.pprint(country)
# Indexing: [Key][Integer], for example:
print(country['GR'][1])
while 1:
sel = input("Enter country code ('q' to Quit): ")
if sel == 'q':
break
else:
if sel.upper() in country:
print(country[sel.upper()])
{Code:{CountryName:, Capital:, Population:]}
country = {}
country['GR'] = {'Name':'Greece',
'Capital':'Athens',
'Pop':'11 milions'}
country['IT'] = {'Name':'Italy',
'Capital':'Rome',
'Pop':'61 milions'}
country['ES'] = {'Name':'Spain',
'Capital':'Madrid',
'Pop':'46 milions'}
# Indexing: [Key][Key], for example:
print(country['GR']['Capital'])
# print the country name and population for all countries
for c in country:
print('Country: ',country[c]['Name'],'\tPopulation: ',country[c]['Pop'])
import pprint
country={}
country['GR'] = {'Name':'Greece',
'Capital':'Athens',
'Pop':11}
country['IT'] = {'Name':'Italy',
'Capital':'Rome',
'Pop':61}
country['ES'] = {'Name':'Spain',
'Capital':'Madrid',
'Pop':46}
# Construct a list with dictionary items
Europe=[country[k] for k in country]
pprint.pprint(Europe)
# Indexing:[Integer][Key], for example:
print(Europe[0]['Capital'])
# Print country name and capital city
for c in Europe:
print('Country: ',c['Name'],'\tCapital: ',c['Capital'])
geo = [{'address_components': [{'name': 'WHITE TOWER',
'types': ['point_of_interest', 'establishment']},
{'name': 'Thessaloniki',
'types': ['locality', 'political']},
{'formatted_address': 'WHITE TOWER, Thessaloniki 546 21, Greece',
'geometry': {'location': {'lat': 40.6257895, 'lng': 22.9495735},
'place_id': 'ChIJN4DZEQM5qBQRULmG-uTW4-c',
'types': ['bus_station',
'transit_station',
'point_of_interest',
'establishment']}}]}]
- What is the type of the geo object?
- How many items does geo contain?
- What is the value object for the key 'address_components'?
- How many items and of what type does the above value object contain?
- What is the length of the 3rd item of the above mentioned value object?
- Write a print to present onscreen the value of the key 'lat'
- Write a print to present onscreen the last item of the value object with key 'types'
. Free learning material
. See full copyright and disclaimer notice