# some basic dict examples. d1 = {} print(f"d1: {d1}") print(f"id(d1): {id(d1)}") print( """d1['a'] = 100 d1[2] = 'hello, world'""") d1['a'] = 100 d1[2] = 'hello, world' print(f"d1: {d1}") print("d1['a'] = [10,20,30]") print(f"d1: {d1}") print(f"d1['a']: {d1['a']}") print( """d1['a'] = 50 d1[1.33] = 90 d1['hello'] = 3.1415""") d1['a'] = 50 d1[1.33] = 90 d1['hello'] = 3.1415 print(f"d1: {d1}") # KeyError: key does not exist in the dict. try: print(f"d1['world']: {d1['world']}") except KeyError: print("key error for d1['world']") # Use the get() to avoid raising KeyError if the key does not exist. print(f"d1.get('a'): {d1.get('a')}") print(f"d1.get('world'): {d1.get('world')}") # key exists? print(f"'hello' in d1: {'hello' in d1}") print(f"'world' in d1: {'world' in d1}") print(f"id(d1): {id(d1)}") d2 = {'a': 100, 'b': 'hello', 'c': 1.25, 'd': 40} print(f"d2: {d2}") # setdefault: set a key to a value only if it does not already exist. print(f"d1.get('e'): {d1.get('e')}") print("d2.setdefault('e', 'orange juice')") d2.setdefault('e', 'orange juice') print(f"d1.get('e'): {d1.get('e')}") print(f"d1.get('a'): {d1.get('a')}") print("d2.setdefault('a', 'apple juice')") d2.setdefault('a', 'apple juice') print(f"d1.get('a'): {d1.get('a')}") # remove a key-value pair. print(f"d2: {d2}") print("del d2['c']") del d2['c'] print(f"d2: {d2}")