5: Dictionaries#
Dictionaries are unordered control structures, meaning that the values they contain are not ordered according to an index, but according to a single key.
A perfect use of dictionaries is to group together “variables” in a single directory. (these variables are not real variables, but keys).
*For example, you can create an inventory dictionary that groups several products (the keys) and their quantities (the values)
inventory = { 'apples': 100,
'bananas': 80,
'pears': 120}
inventory.values()
dict_values([100, 80, 120])
inventory.keys()
dict_keys(['apples', 'bananas', 'pears'])
len(inventory)
3
Here is how to add a key/value association in our dictionary (be careful if the key already exists it is replaced)
inventory['apricots'] = 30
print(inventory)
{'apples': 100, 'bananas': 80, 'pears': 120, 'apricots': 30}
Warning : if you look for a key that doesn’t exist in a dictionary, python returns an error. To avoid this, you can use the get() method
inventory.get('peaches') # does not exist
inventory.get('apples') # apple exists
100
the pop() method allows you to remove a key from a dictionary while returning the value associated to the key.
apricots = inventory.pop("apricots")
print(inventory) # no longer contains a key apricots
print(apricots) # apricots contains the value of the dictionary
{'apples': 100, 'bananas': 80, 'pears': 120}
30
To use a for loop with a dictionary, it is useful to use the items() method which returns both keys and values
for key, value in inventory.items():
print(key, value)
apples 100
bananas 80
pears 120
Exercise and Solution#
Implement a function sort(folder, value) that places a value in a dictionary according to its sign
folder = { 'negative':[],
'positive':[]
}
def sort(folder, value):
return folder
Solution#
Show code cell content
def sort(folder, value):
if value >=0:
folder['positive'].append(value)
else:
folder['negative'].append(value)
return folder
sort(folder, 9)
{'negative': [], 'positive': [9]}