Python Dictionaries Flashcards
What is a python dictionary?
A collection which is unordered, changeable and indexed
What is the time complexity to access a key in a dictionary?
O(1) time complexity
How are dictionaries recorded in memory?
A dictionary is recorded in memory as a hash table.
What is a hash table?
A hash table is a way of doing key-value lookups. You store the values In an array, and then use a hash function to find the index of the array cell that corresponds to your key-value pair.
What are collisions in a hash table?
Different keys have the same hash value.
Ways to add key value pairs to a dictionary and update
- myDict[‘age’] = 17
side note: o(1) time complexity
Set a new key value if it doesnt exist in Dictionary
myDict.setdefault(key, value)
if the key value already exists it does not set the value.
Different ways to pull values from a dictionary
- myDict[key]: this will pull the value. if the key does not exist then it will return an error.
- myDict.get(key, value): This will pull the value and return None if it does not exist. if value is set then this will be the default value.
simple way to traverse over keys in dict
for key in myDict:
print(key, dict[key])
O(n) time complexity
How to search for a value in a dictionary
def searchDict(dict, value):
for key in dict:
if dict[key] == value:
return key, value
return None
O(n)
O(1) for space complexity.
What are the 4 ways to delete a value or values from a Dictionary
- myDict.pop(key):
removes and returns the keys value - myDict.popitem():
removes a random key - myDict.clear():
removes all the keys in the dictionary - del myDict[key]:
removes a specific key from the dictionary
method used to create a copy of a dictionary
the .copy()
creates a copy of the dictionaries. The original one will not change when using this
How do you create a dictionary using a list of keys
{}.fromkeys(sequence[], value])
- value is optional
- values will be None if the value is not set
how to get a dictionary as a list of tuples in python. Good for iteration.
.items() method
result example: [(key1, value1), (key2, value2)]
How to get all the keys in a dictionary
dict.keys() will return a list of keys