Lesson 3 of 4
Store values under meaningful keys with dictionaries: look values up, add and change entries, and build records for materials and samples.
About 30 minutes
[] and get()Lists and tuples identify items by position. That works when order is what matters, but often you want to look something up by name. Remembering that density is item 2 in a list is error-prone; looking up "density" is not. A dictionary stores key-value pairs: each unique key maps to a value, like a word and its definition in a real dictionary.
Dictionaries are written with curly braces. Each pair is written key: value, and pairs are separated by commas. Keys are usually strings; values can be anything, including lists or other dictionaries.
copper = { "symbol": "Cu", "density": 8.96, # g/cm³ "melting_point": 1085, # °C "structure": "FCC",}print(copper["density"])print(len(copper))Put a key in square brackets to get its value. If the key doesn't exist, Python raises a KeyError. When a key might be missing, use the get() method instead: it returns None, or a default value you choose, rather than stopping the program.
copper = {"symbol": "Cu", "density": 8.96}print(copper.get("density"))print(copper.get("band_gap"))print(copper.get("band_gap", "not recorded"))The in operator checks whether a key is present. It does not look at the values.
copper = {"symbol": "Cu", "density": 8.96}print("density" in copper)print("Cu" in copper) # "Cu" is a value, not a keyDictionaries are mutable. Assigning to a key that doesn't exist yet adds a new pair; assigning to an existing key replaces its value. del removes a pair, and pop(key) removes it and returns its value. update() adds or changes several pairs at once from another dictionary.
sample = {"id": "Al-07", "mass": 2.70}sample["volume"] = 1.0 # add a new keysample["mass"] = 2.71 # change an existing valuesample.update({"operator": "AR", "temperature": 293})del sample["operator"] # remove a keyprint(sample)Keys are unique
Three methods give you views of a dictionary's contents: keys() gives the keys, values() gives the values, and items() gives each pair as a (key, value) tuple. Wrap them in list() to see them as ordinary lists. Since values() gives all the values, you can pass it straight to functions such as max() and sum().
melting_points = {"Al": 660, "Cu": 1085, "Fe": 1538}print(list(melting_points.keys()))print(list(melting_points.values()))print(list(melting_points.items()))print(max(melting_points.values()))In the Control Flow module you will use items() with a for loop to go through every key-value pair in turn.
Dictionaries are ideal for describing one thing with several named properties. Values can themselves be lists or dictionaries, so you can build detailed records. Chain the square brackets to reach values inside.
A material record with nested mechanical properties and a list of measured hardness values.
steel = { "name": "AISI 304", "composition": {"Fe": 70.0, "Cr": 19.0, "Ni": 9.0}, # wt% "mechanical": {"youngs_modulus": 193, "yield_strength": 215}, # GPa, MPa "hardness": [201, 198, 205], # HV}print(steel["name"])print(steel["composition"]["Cr"], "wt% Cr")print(steel["mechanical"]["yield_strength"], "MPa")print(max(steel["hardness"]), "HV maximum")Quotes inside f-strings
f"{enzyme['name']}". Using the same quote as the f-string itself can confuse older versions of Python.Choose an answer and press Check answer. You can retry as often as you like.