#!/usr/bin/env python # Dictionaries can be declared with curly brackets or the dict() method numbers = {} words = dict() # We can also declare a dictionary with items in it numbers = { '2': 'two', '1': 'one', '4': 'four', '3': 'three', '5': 'five' } # print(numbers) # This will print the keys # The keys of a list are unordered # for n in numbers: # print(n) # Printing using list comprehension # l = list(range(10)) # [print(i) for i in l] # [print(k) for k in numbers.keys()] # [print(k) for k in numbers.values()] # [print(k) for k in numbers.items()] # The key of a dictionary must either be a string or a tuple (something that is immutable) words['ornithic'] = 'nothing' words['ornithic'] = 'of, like or pertaining to birds' words['custos'] = 'guardian, custodian or keeper, especially of convents or monasteries' words['declivity'] = 'place that slopes downwards; inclination downwards' words['kobold'] = 'spirit of the mines' words['Valhalla'] = 'the hall of Odin into which the souls of heroes slain in battle and others who have died bravely are received.' [print(item) for item in words.items()] # Determine if a value exists # print('bob' in words) # print('Valhalla' in words) # Set default words.setdefault('python', 'Not yet defined.') [print(item) for item in words.items()] # This works but is dangerous print('kobold: ', words['kobold']) print('valhalla: ', words.get('valhalla', 'not in dictionary')) print('Valhalla: ', words.get('Valhalla', 'not in dictionary')) # A worse alternative don't do this if 'Valhalla' in words: print(words['Valhalla']) else: print('not in dictionary') # Pretty printing import pprint pprint.pprint(words) pprint.pprint(numbers)