""" Ex. 6.7 from 'A primer on... Read info from a file into a nested dictionary. File is structured in a way that makes it difficult to process each line with the split-function. We can instead use string indexing. Finally, print the info from the dictionary to the screen. Purpose of the exercise: * Read a file with a different structure (cannot use 'split') * Create a nested dictionary * Traverse a nested dictionary * f-string formatting """ humans = {} with open('human_evolution.txt') as infile: for line in infile: if line[0] == 'H': name = line[:20].strip() # key in "main" dict #the following will be values in "internal" dict: when = line[20:37].strip() height = line[37:50].strip() mass = line[50:62].strip() brain = line[62:].strip() #create a dict with these values, and keys as given in the exercise: info = {'when':when, 'height':height, 'weight':mass, 'brain volume':brain} #add this dict as a value in the main dict, with name as value: humans[name] = info for key, value in humans.items(): name = key w = value['when'] h = value['height'] m = value['weight'] b = value['brain volume'] #suitable f-string for nice formatting: line = f"{name:<20} {w:<14} {h:<10} {m:<10} {b:<}" print(line) """ Terminal> python humans.py H. habilis 2.2 - 1.6 1.0 - 1.5 33 - 55 660 H. erectus 1.4 - 0.2 1.8 60 850 (early) - 1100 (late) H. ergaster 1.9 - 1.4 1.9 700 - 850 H. heidelbergensis 0.6 - 0.35 1.8 60 1100 - 1400 H. neanderthalensis 0.35 - 0.03 1.6 55 - 70 1200 - 1700 H. sapiens sapiens 0.2 - present 1.4 - 1.9 50 - 100 1000 - 1850 H. floresiensis 0.10 - 0.012 1.0 25 400 """