Week 7:¶

Dictionaries:¶

Creating a dictionary

In [ ]:
new_dict = {} # Start with an empty dict and add key-value pairs to it
new_dict['key1'] = 'value1' # Call a value by 'indexing' the dictionary by its key

new_dict
{'key1': 'value1'}
In [ ]:
# Read in a dict from lists
key_list = ['key1', 'key2']
value_list = ['value1', 'value2']

new_dict = {}
for i in range(0,len(key_list)):
    new_dict[key_list[i]] = value_list[i]
    
new_dict
{'key1': 'value1', 'key2': 'value2'}
In [ ]:
# Zip two lists into a dict:
key_list = ['key1', 'key2']
value_list = ['value1', 'value2']

new_dict = dict(zip(key_list, value_list))
print(new_dict)

# Return a dictionary's keys
print(new_dict.keys())

# Return a dictionary's values

print(new_dict.values())
{'key1': 'value1', 'key2': 'value2'}
dict_keys(['key1', 'key2'])
dict_values(['value1', 'value2'])

Complex dictionaries:¶

Dictionary values can be complex objects:

In [ ]:
# Dictionary of lists
my_dict = {'plants': ['maple', 'pine', 'snowberry'], 'fungi': ['amanita', 'morel']}
print(my_dict)
print(my_dict['plants'][2]) # Index a complex dictionary with a series of [ ] brackets
{'plants': ['maple', 'pine', 'snowberry'], 'fungi': ['amanita', 'morel']}
snowberry
In [ ]:
# Dictionary of dictionaries
my_dict = {'plants': {'angiosperm':'maple', 'confier':'pine'}, 'fungi': {'basidio': 'amanita', 'asco': 'morchella'}}
print(my_dict)
print(my_dict['fungi']['asco'])
{'plants': {'angiosperm': 'maple', 'confier': 'pine'}, 'fungi': {'basidio': 'amanita', 'asco': 'morchella'}}
morchella
In [ ]:
# Iterate through a dictionary
my_dict = {'plants': {'angiosperm':'maple', 'confier':'pine'}, 'fungi': {'basidio': 'amanita', 'asco': 'morchella'}}

for key in my_dict:
    print("Level 1:", key)
    for x in my_dict[key]:
        print("Level 2:", x)
        print("Level 3:", my_dict[key][x])
Level 1: plants
Level 2: angiosperm
Level 3: maple
Level 2: confier
Level 3: pine
Level 1: fungi
Level 2: basidio
Level 3: amanita
Level 2: asco
Level 3: morchella