Dictionaries
Dictionaries are a kind of sequence which contains named key-pairs. It is a bit like having a list of named variables.
ages = { "Bob" : 50, "Ruth" : 28, "Chris" : 32, "Charlie" : 9 }
Dictionaries can be accessed in a similar way to lists, albeit using the keyname in place of a numeric index.
print(ages["Bob"])
50
They can also be modified in a similar way.
ages["Ruth"] += 1
print(ages["Ruth"])
29
They can be iterated through like a list as well, while also iterating through keys.
for k,v in ages.items():
print(k, v)
Bob 50
Ruth 29
Chris 32
Charlie 9
However, by default, only keys are iterated through:
for k in ages:
print(k, ages[k])
Dictionaries can also be appended by defining another key any time after initial declaration:
ages["Blues"] = 90
print(list(ages.items()))
[('Bob', 50), ('Ruth', 29), ('Chris', 32), ('Charlie', 9), ('Blues', 90)]
An easy way to pass a large amount of data into a function without great confusion is to turn it into a dictionary. In addition, dictionaries can be returned from functions to get the result of multiple calculations from a single function.
def similarity_table(*nums):
truths = {}
for num in nums:
comparisons = [num == i for i in nums]
truths[str(num)] = comparisons
return truths
print(similarity_table(1, 1, 2, 2, 3, 4, 5, 6))
This will output a dictionary including each number provided to the function, along with whether or not it is the same as each other number in the parameters list:
{'1': [True, True, False, False, False, False, False, False], '2': [False, False, True, True, False, False, False, False], '3': [False, False, False, False, True, False, False, False], '4': [False, False, False, False, False, True, False, False], '5': [False, False, False, False, False, False, True, False], '6': [False, False, False, False, False, False, False, True]}
When in doubt about how to organize data, a dictionary is likely a good idea.