Dictionary in Python
Dictionary in Python
Dictionary in Python
Python dictionary is an unordered collection of items. While other compound data types have only value as
an element, a dictionary has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.
# Output: {2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
# Throws Error
# print(squares)
When you run the program, the output will be:
16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}
fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
Remove the item with key and return its value or d if key is not found. If d is not provided
pop(key[,d]) and key is not found, raises KeyError.
popitem() Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty.
If key is in the dictionary, return its value. If not, insert key with a value of d and
setdefault(key[,d]) return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys.
Function Description
all() Return True if all keys of the dictionary are true (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
Here are some examples that uses built-in functions to work with dictionary.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: 5
print(len(squares))
# Output: [1, 3, 5, 7, 9]
print(sorted(squares))