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
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
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
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
getting a list of just the values in a dictionary
dict.values()
How to combine a dictionary to another dictionary
dict1.update(dict2)
How to determine if a key exists in the dictionary
key in dict
determine if a value is in a dictionary
value in dict.values()
returns only true when every value in the dictionary is true
all(dict)
if any element of a collection is true in a dict it will return true.
any(dict)
count the number of keys in a dictionary
count the number of values in a dictionary
: len(dict1) returns number of keys
: len(dict.values()) returns number of keys
how to order a dictionary keys
sorted(myDict , reverse=False, key=None)
- reverse will reverse the order of the sort
- key will change how the sort function is sorting the keys
What are the key differences between a list and a dictionary