Python Dictionary

In [183]:
# How to create a dictionary of countries in America and their capitals?
america = {'Country': 'Capital', 'Canada': 'Ottawa', 'Mexico':'Ciudad de México', 'United States':'Washington, D.C'}
In [184]:
# Print countries in America and their capitals 
print(america)
{'Country': 'Capital', 'Canada': 'Ottawa', 'Mexico': 'Ciudad de México', 'United States': 'Washington, D.C'}
In [185]:
# How to get the capital of Mexico? 
#  use the keys inside a [] instedd of the index as in lists and tuples
#  the countries are the keys while the capitals are the values
print(america['Country'])
print(america['Mexico'])
Capital
Ciudad de México
In [186]:
# How to get the capital of Mexico? We can also use .get()
print(america.get('Country'))
print(america.get('Mexico'))
Capital
Ciudad de México
In [204]:
# How to know the keys in a dictionary?
print(america.keys())
dict_keys(['Country', 'Canada', 'Mexico', 'Brazil'])
In [205]:
# How to know the values in a dictionary?
print(america.values())
dict_values(['Capital', 'Toronto', 'Ciudad de México', 'Brasília'])
In [206]:
# How to know the items in a dictionary?
print(america.items())
dict_items([('Country', 'Capital'), ('Canada', 'Toronto'), ('Mexico', 'Ciudad de México'), ('Brazil', 'Brasília')])
In [190]:
# How many items (key-value pairs) are in a dictionary?
len(america)
Out[190]:
4
In [191]:
# How to change the capital of Canada?
america['Canada'] = 'Toronto'
print(america)
{'Country': 'Capital', 'Canada': 'Toronto', 'Mexico': 'Ciudad de México', 'United States': 'Washington, D.C'}
In [192]:
# How to add Brazil and its capital to America?
america['Brazil'] = 'Brasília'
print(america)
{'Country': 'Capital', 'Canada': 'Toronto', 'Mexico': 'Ciudad de México', 'United States': 'Washington, D.C', 'Brazil': 'Brasília'}
In [193]:
# How to delete the United States from America?
del america['United States']
print(america)
{'Country': 'Capital', 'Canada': 'Toronto', 'Mexico': 'Ciudad de México', 'Brazil': 'Brasília'}