Dictionary
my_dict = dict()
my_dict = {}
Set Item O(1) -> O(n)
Get Item O(1) -> O(n)
my_dict[key] # Returns the item with the key, KeyError is not in dict
my_dict.get(key[, default]) # Returns the value for the key if in the dictionary
# Otherwise the provided default or None if not provided
Set Item Pattern
for i in my_dict:
# if key is not present then it genrate error, or if first time
# key come then it generate error and goto except block
# so initilize char with 1 value
try:
my_dict[i] += 1
except:
my_dict[i] = 1
Dict Views
Items
for key, val in my_dict.items():
print(key, val)
if (key, value) in my_dict.items() # Check if (key, value) tuple in dict
Keys
for key in my_dict.keys()
print(key)
if key in my_dict.keys() # Check if key in keys
Values
for val in my_dict.values()
print(val)
if val in my_dict.values() # Check if val in values
Delete Item O(1) -> O(n)
Check in Dict
key in my_dict # True if my_dict has a key, else False
key not in my_dict
Size
Clear