Expedia Code Academy
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):
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)
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
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.
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:
inventory = {'apples': 320, 'pears': 228, 'bananas': 420}
print(inventory.keys())
# will print ['apples', 'pears', 'bananas']
print(inventory.values())
# will print [320, 228, 420]
inventory = {'apples': 320, 'pears': 228, 'bananas': 420}
'apples' in inventory # will return True
'oranges' in inventory # will return False
inventory = {'apples': 3, 'pears': 2, 'bananas': 0}
how_many = input('How many items would you like to buy?')
how_many = int(how_many) # convert string to number (int = integer)
{'e': 2, 'x': 1, 'p': 1, 'd': 1, 'i': 1, 'a': 1}