''' 20210927 R. Dawes Dictionaries in Python - Part 1 ''' # create a dictionary and store some key : value pairs animals = { 'Hudson' : 'dog', 'Lindor':'cat', 'Gus':'sloth', 'Ed':'horse', 'Praxiteles': 'turtle', 'Rupert':'canary', 'Silver': 'dog'} print(animals) print("\nLength of 'animals' dictionary:",len(animals)) print('\n') # iterate through the keys in the dictionary for pet in animals: print(pet, 'is a', animals[pet]) print('\n') # identify the type if type(animals) is dict: print("It's a dictionary") else: print("It's not") print('\n') # add a new key and value animals['Nemo'] = 'clownfish' for pet in animals: print(pet, 'is a', animals[pet]) print('\n') # check to see if a key is in the dictionary pet_name = "Simon" if pet_name in animals: print (pet_name,"is a", animals[pet_name]) else: print(pet_name, 'is unknown') print('\n') # get a 'list' of the keys animals_names = animals.keys() print("'animals' key values:",animals_names) print('\n') # convert the key list into a normal list animals_names_list = list(animals_names) print(animals_names_list) print(animals_names_list[3]) print(animals[animals_names_list[3]]) print('\n') # remove a key : value pair from the dictionary print("Removing 'Ed' from the dictionary") del animals['Ed'] if 'Ed' not in animals: print('Ed is gone.') else: print('Ed is still there') print('\n') # iterate through the key : value pairs (not just the keys) for k, v in iter(animals.items()): if v == 'dog': print(k,'is a dog')