Home      |       Contents       |       About

Prev: Constructing dictionaries       |       Next: Dictionary vs. List

Combining dictionary and list

  • By combining dictionaries and lists in a single object many powerful data structures can be constructed depending on the application. Some illustrative examples follow.

Dictionary with lists as values

  • In the following example lists are used as values in a dictionary
  • 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

  • Also string upper() method is used to capitalize user's input
In [1]:
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()])       
   
{'ES': ['Spain', 'Madrid', 46],
 'GR': ['Greece', 'Athens', 11],
 'IT': ['Italia', 'Rome', 61]}
Athens
Enter country code ('q' to Quit): GR
['Greece', 'Athens', 11]
Enter country code ('q' to Quit): q

Dictionary with dictionaries as values

  • Dictionaries can also be used as values in a dictionary
  • Below the dictionary key:value pairs are of the form:
      {Code:{CountryName:, Capital:, Population:]}
In [2]:
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'])
Athens
Country:  Italy 	Population:  61 milions
Country:  Greece 	Population:  11 milions
Country:  Spain 	Population:  46 milions

Lists of dictionaries

  • In the following example dictionaries are used as list items
In [3]:
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'])
[{'Capital': 'Rome', 'Name': 'Italy', 'Pop': 61},
 {'Capital': 'Athens', 'Name': 'Greece', 'Pop': 11},
 {'Capital': 'Madrid', 'Name': 'Spain', 'Pop': 46}]
Rome
Country:  Italy 	Capital:  Rome
Country:  Greece 	Capital:  Athens
Country:  Spain 	Capital:  Madrid

(4) Google maps API

  • Several web services make APIs available using a combined list-dictionary structure
  • For example, Google maps API returns geographical information organized in complex list-dictionary structure
  • The geo object below is only a selected part of the whole object returned
In [ ]:
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']}}]}]

Practice

  • Using the geo object above try to answer the following questions (write also the code to present onscreen the appropriate values):
    1. What is the type of the geo object?
    2. How many items does geo contain?
    3. What is the value object for the key 'address_components'?
    4. How many items and of what type does the above value object contain?
    5. What is the length of the 3rd item of the above mentioned value object?
    6. Write a print to present onscreen the value of the key 'lat'
    7. 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