Creating Python Dictionary
Creating Python Dictionary
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
As you can see from above, we can also create a dictionary using the built-in dict() function.
Accessing Elements from Dictionary
While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside
square brackets [] or with the get() method.
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other hand,
the get() method returns None if the key is not found.
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# KeyError
print(my_dict['address'])
Output
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value)
pair is added to the dictionary.
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the
provided key and returns the value.
The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All
the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
# Removing elements from a dictionary
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
Output
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
Traceback (most recent call last):
File "<string>", line 30, in <module>
print(squares)
NameError: name 'squares' is not defined
Methods that are available with a dictionary are tabulated below. Some of them have already been used in the
above examples.
Method Description
fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
Removes the item with the key and returns its value or d if key is not found. If d is not provide
pop(key[,d])
and the key is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key[,d] Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a valu
) of d and returns d (defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly
braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
Output
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
utput
print(odd_squares)
Run Code
Output
We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for
the keys and not for the values.
# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
True
True
False
1
9
25
49
81
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform
different tasks.
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 use built-in functions to work with a dictionary.
# Output: False
print(all(squares))
# Output: True
print(any(squares))
# Output: 6
print(len(squares))
# Output: [0, 1, 3, 5, 7, 9]
print(sorted(squares))
Run Code
Output
False
True
6
[0, 1, 3, 5, 7, 9]