Dictionaries Flashcards
What are dictionaries and how are they used?
Dictionaries (type dict) is an unordered data structure. They are of the form :
key: value
Key - must be immutable (tuples, strings, int, float, bool)
Value - can be anything
Dictionaries are created by putting curly brackets around key:value
{key1: value1, key2:value2…}
Dictionaries can be within dictionaries (having a dictionary as a value)
users = {‘0323442785’: {‘first name’: ‘Sebastian’,
‘last name’: ‘Goodfellow’,
‘address’: ‘555 Code Street’,
‘phone number’: ‘555-7654’},
‘9764327492’: {‘first name’: ‘Ben’,
‘last name’: ‘Kinsella’,
‘address’: ‘555 Python Street’,
‘phone number’: ‘555-2345’}
Dictionary Operators
Dictionaries are mutable (entries can be added, modified and removed)
Take: grades = {“Tina”: “A+”]
Indexing - index with keys, retrieves the value associated with the key
grades[“Tina”]
“A+”
you CAN NOT index two keys at once, for example:
a = {‘Lowry’:1,’VanVleet’:2,’Siakam’:3}
print(a[‘Lowry’,’VanVleet’])
error
Add/ Modify an Entry - modifies the entry if exists, adds to the end if it doesn’t
grades[“John”]= “B+”
grades
{“Tina”: “A+”, “John”: “B+”}
Delete Operations - Removes a key and it’s value, used del operator
del grades[“Tina”]
grades
{“John”: “B+”}
In Operator - Tests for existence of key in dictionary (doesn’t check for values)
“John” in grades
True
if “John” in grades
What are some dictionary methods and how are they used?
.keys()
Returns a set-like object containing all keys found in a given dictionary.
.values()
Returns a list-like object containing all values found in a given dictionary.
.items()
Returns a list-like object containing tuples of key-value-pairs.
.clear()
Remove all the elements from a dictionary.
.get()
Returns the value of the key entry from the dict. (like dict[key] but works if key doesn’t exist without giving an error)
.update()
Merges a dictionary dict_1 with another dictionary dict_2. Existing entries in dict_1 are overwritten if the same keys exist in dict_2.
.pop()
Removes and returns the value corresponding to the specified key from the dictionary. If key does not exist, then None or a user-specified default is returned.
Explain iterating through dictionaries
The default interation for a dicitonary is over the keys.
If you want to be explicit and write slightly more readable code, you can use the .keys() method.
To iterate through the dictionary values, you can use the .values() method.
If you want to iterate through the keys and values at the same time, you can use the .items() method.