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#
Operator | Use | Explanation |
---|
[] | myDict[k] | Returns the value associated with k , otherwise its an error |
in | key in adict | Returns True if key is in the dictionary, False otherwise |
del | del adict[key] | Removes the entry from the dictionary |
Additional Operations#
Method Name | Use | Explanation |
---|
keys | adict.keys() | Returns the keys of the dictionary in a dict_keys object |
values | adict.values() | Returns the values of the dictionary in a dict_values object |
items | adict.items() | Returns the key-value pairs in a dict_items object |
get | adict.get(k) | Returns the value associated with k , None otherwise |
get | adict.get(k,alt) | Returns the value associated with k , alt otherwise |
Time Complexity of Operations#
operation | Big-O Efficiency |
---|
copy | O(n) |
get item | O(1) |
set item | O(1) |
delete item | O(1) |
contains (in) | O(1) |
iteration | O(n) |
Examples#
Iterating a Dictionary#
Check if a Key Exists#
Sorting a Dictionary by Keys#