Python 101

Week 6:
Dictionaries

Expedia Code Academy

Dictionaries

I have a dictionary, and I want to look up the meaning of the word hotel.

You can describe this data as having a key (hotel) and a value (the definition). This is a data structure in Python!

Here's a dictionary representing people (keys) and their favourite animals (values):

Dictionaries

So far we have seen lists, where we grab elements using their numbered position, or index.

Dictionaries are similar to lists, except you access the elements using unordered keys


                eng_dict = {} # let's create an English dictionary

                # then add words to it
                eng_dict['hotel'] = 'An establishment providing accommodation.' 
                eng_dict['flight'] = 'The process of flying through the air.'

                print(eng_dict)
              

Dictionaries

You can also create a dictionary with data in it:


                # We can define a dictionary in one line too
                eng_dict = {
                  'hotel': 'An establishment providing accommodation',
                  'flight': 'The process of flying through the air'
                }

                print(eng_dict['hotel']) # to print a value from the dictionary
              

(⭐️) 6a. Create a dictionary of the class' favourite animals

Dictionary operations

We can also modify existing dictionaries - the syntax is the same as adding new values.


                eng_dict = {
                  'hotel': 'An establishment providing accommodation',
                  'flight': 'The process of flying through the air'
                }

                eng_dict['hotel'] = 'An establishment providing accommodation, buy now at Hotels.com!'

                # We can find the number of key-value pairs in the dictionary
                len(inventory) # just like for lists
              

(⭐️⭐️) 6b. Use input() to add someone's name and their favourite animal dynamically.

Dictionary exercise

(⭐️⭐️) 6c. Let's access data in a dictionary!

            hotel = {
                'name': 'Corinthia Hotel',
                'amenities': ['Indoor pool', 'Fitness centre', 'Spa'],
                'top spots': [
                    {'name': 'Trafalgar Square', 'proximity': 300},
                    {'name': 'London Eye', 'proximity': 450},
                    {'name': 'Buckingham Palace', 'proximity': 1200}
                 ]
            }
          
How can you:
  • Access the hotel name?
  • Find out how many amenities it has?
  • Find out the names of the top spots near it?
  • Find out all the top spots within 500 metres reach?

Appendix: Dictionary methods

We can get lists of all keys or all values.


                inventory = {'apples': 320, 'pears': 228, 'bananas': 420}

                print(inventory.keys())
                # will print ['apples', 'pears', 'bananas']
                print(inventory.values())
                # will print [320, 228, 420]
              

Or we can check if a dictionary contains a given key, just like in lists.


                inventory = {'apples': 320, 'pears': 228, 'bananas': 420}

                'apples' in inventory # will return True
                'oranges' in inventory # will return False
              

Appendix: Dictionary exercises


              inventory = {'apples': 3, 'pears': 2, 'bananas': 0}
          
  • (⭐️⭐️) 6d. Let's go shopping! For this exercise use the following dictionary:
    • The program should handle the following scenario:
    • A shopper would like to buy 1 item. Take user input of what that item is.
      Assume that the user will type 'apples', 'pears' or 'bananas'!
    • Update the inventory to reflect that purchase - i.e. if someone buys apples, their value would go from 3 to 2.
  • (⭐️⭐️⭐️) 6e. Add the following functionality to your shopping program:
    • i. If that item doesn't exist, let the user know.
    • ii. If that item is sold out, let the user know.
    • iii. (🔥) Also ask the user for how many items they'd like to buy. Hint: you'll need
      
                            how_many = input('How many items would you like to buy?')
                            how_many = int(how_many)  # convert string to number (int = integer)
                          

Appendix: Dictionary creation exercises

  • (⭐️️️⭐️️️⭐️) 6f. Write a program that tracks the count of the letters from a string.

    Given the string 'expedia' the expected output is:
    
                          {'e': 2, 'x': 1, 'p': 1, 'd': 1, 'i': 1, 'a': 1}