Dictionary in Python
Dictionary in Python
Dictionary in Python
Website: https://pythonlife.in/
Python Dictionary
Python dictionary is an unordered collection of items. Each item of a
dictionary has a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
in
An item has a key and a corresponding value that is expressed as a pair
(key: value).
e.
While the values can be of any data type and can repeat, keys must be of
immutable type (string, number or tuple with immutable elements) and
lif
must be unique.
on
# empty dictionary
my_dict = {}
th
As you can see from above, we can also create a dictionary using the built-in
dict() function.
2
Website: https://pythonlife.in/
in
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}
# Output: Jack e.
lif
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
on
print(my_dict['address'])
elements
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.
.in
at once, using the clear() method.
We can also use the del() keyword to remove individual items or the
entire dictionary itself. ife
# Removing elements from a dictionary
nl
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
ho
print(squares)
# remove an arbitrary item, return (key,value)
# Output: (5, 25)
print(squares.popitem())
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# Throws Error
print(squares)
4
Website: https://pythonlife.in/
.in
Method Description
copy()
ife
Returns a shallow copy of the dictionary.
nl
get(key[,d]) Returns the value of the key. If the key does not exist, returns d
ho
items() Return a new object of the dictionary's items in (key, value) format.
update([other]) Updates the dictionary with the key/value pairs from other, overwriting
existing keys.
# Dictionary Comprehension
.in
squares = {x: x*x for x in range(6)}
print(squares) ife
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
nl
A dictionary comprehension can optionally contain more for
or if statements.
ho
dictionary.
Py
.in
print(2 not in squares)
# membership tests for key only not value
# Output: False
ife
print(49 in squares)
Iterating Through a Dictionary
nl
We can iterate through each key in a dictionary using a for loop
# Iterating through a Dictionary
ho
Output
Py
1
9
25
49
81