Dictionaries

Dictionaries are collections of key-value pairs. It supports mixed types of key-value pairs.

Example of a dictionary: fruitColors = {'apple': 'red', 'orange': 'orange', 'pear': 'green'}.

Useful Operations#

OperatorUseExplanation
[]myDict[k]Returns the value associated with k, otherwise its an error
inkey in adictReturns True if key is in the dictionary, False otherwise
deldel adict[key]Removes the entry from the dictionary

Additional Operations#

Method NameUseExplanation
keysadict.keys()Returns the keys of the dictionary in a dict_keys object
valuesadict.values()Returns the values of the dictionary in a dict_values object
itemsadict.items()Returns the key-value pairs in a dict_items object
getadict.get(k)Returns the value associated with k, None otherwise
getadict.get(k,alt)Returns the value associated with k, alt otherwise

Time Complexity of Operations#

operationBig-O Efficiency
copyO(n)
get itemO(1)
set itemO(1)
delete itemO(1)
contains (in)O(1)
iterationO(n)

Examples#

Iterating a Dictionary#

for key, value in dict.items():
print(key)
print(value)

Check if a Key Exists#

if key in dictionary:
do_smth()

Sorting a Dictionary by Keys#

d = {'apple':'red', 'orange':'orange'}
sorted(my_dict) # returns ['apple', 'orange']