Skip to main content

Python Dictionary

Python dictionary is an unordered collection of elements.

  • Python Dictionary is used there are a huge amount of data because Dictionaries are optimized for retrieving data.
  • Each key is used to retrieve the respective value (and not vice versa).
  • key-value pairs in a dictionary are not ordered or sortable.

Create Python Dictionary

A dictionary is created using curly brackets {}. In addition, you can directly define a dictionary with some key-value pairs.

An item has a key and a corresponding value that is expressed as a pair (key: value).

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 must be unique.

You can also create a dictionary using the built-in dict() function.

# empty dictionary
my_dict = {}

# dictionary with integer keys
my_dict = {1: 'Tutorial', 2: 'Reference'}

# dictionary with mixed keys
my_dict = {'name': 'Tom', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'Tutorial', 2:'Reference'})

# from sequence having each item as a pair
my_dict = dict([(1,'Tom'), (2,'Ryan')])

Access Dictionary Elements

The dictionary uses keys to access values. Keys can be used inside square brackets [] or with the get() method.

  • If square brackets [] are used, KeyError is raised in case a key is not found in the dictionary.
  • The get() method returns None if the key is not found.
my_dict = {1:'value','key':2, 'my-key':'my-value'}

print(my_dict[1]) # value
print(my_dict['key']) # 2

# Trying to access keys which doesn't exist throws error
print(my_dict.get('address')) # None

# KeyError
print(my_dict['address'])
# Traceback (most recent call last):
# File "<string>", line 11, in <module>
# KeyError: 2

Dictionary Manipulation

Dictionaries are mutable.

So, it is possible to add new items or to change the value of existing items using an assignment operator.

Add Dictionary Elements

If the key is not present, then a new key: value pair is added to the dictionary.

my_dict = {'name': 'Tom', 'age': 24}

# add element
my_dict['address'] = 'New York'

print(my_dict) # {'name': 'Tom', 'age': 24, 'address': 'New York'}

Change Dictionary Elements

If the key is already present, then the existing value gets updated.

my_dict = {'name': 'Tom', 'age': 24}

# update value
my_dict['age'] = 30

print(my_dict) # {'name': 'Tom', 'age': 30}

Delete Dictionary Elements

  • The pop() method is used to remove a particular element from a dictionary. This method removes an element with the given key and returns the value.
  • The popitem() method can be used to remove and return an arbitrary pair of (key, value) elements from the dictionary.
  • The clear() method removes all elements at once.
  • The del keyword can be used to remove individual items or the entire dictionary itself.
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}
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)
# NameError: name 'squares' is not defined

Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.

List comprehension consists of a pair of expressions (key: value) followed by a for statement inside curly brackets {}.

For example, create a dictionary with the cubes of each integer element:

cubes = {x: x*x*x for x in range(5)}
print(cubes) # {0: 0, 1: 1, 2: 8, 3: 27, 4: 64}

and this code is equivalent to:

cubes = {}
for x in range(5):
cubes[x] = x*x*x
print(cubes) # {0: 0, 1: 1, 2: 8, 3: 27, 4: 64}

A dictionary comprehension can optionally contain more for or if. An optional if statement can filter out items for the new dictionary. For example:

odd_cubes = {x: x*x*x for x in range(11) if x % 2 == 1}

print(odd_cubes) # {1: 1, 3: 27, 5: 125, 7: 343, 9: 729}
note

Dictionary Built-in Functions

Built-in functions such as all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform various tasks.

FunctionDescription
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.
len()Return the length (the number of items) in the dictionary.
cmp()Compares items of two dictionaries. (Not available in Python 3)
sorted()Return a new sorted list of keys in the dictionary.

Other Dictionary Operations

Dictionary Membership Test

The keyword in is used to check whether an element exists in a dictionary.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

print(1 in squares) # True
print(2 not in squares) # True
print(49 in squares) # False
note

The keyword in checks only for keys and not for values of the dictionary.

Iterating Through a Dictionary

Using a for loop, it is possible to iterate each element of a dictionary.

squares = {1: 1, 3: 9, 5: 25}
for i in squares:
print(squares[i])

Output

1
9
25

Summary of Python Dictionary Methods

Python has many useful dictionary methods that make it very easy to work with dictionaries.

The following are some of the commonly used dictionary methods.

MethodDescription
clear()Removes all items from the dictionary.
copy()Returns a shallow copy of the dictionary.
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.
keys()Returns a new object of the dictionary's keys.
pop(key[,d])Removes the item with the key and returns its value or d if key is not found. If d is not provided 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 value of d and returns d (defaults to None).
update([other])Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values()Returns a new object of the dictionary's values