Python Dictionary

Contents

Python Dictionary#

Learn everything about Python dictionaries; how they are created, accessing, adding, removing elements from them and various built-in methods.

What is Dictionary in Python?#

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.

Example:

>>> dict = { }  #empty dictionary
>>> dict = {1:'Python',2:'Java',3:'C++'}
  • Dictionary is mutable i.e., value can be updated.

  • Key must be unique and immutable. Value is accessed by key. Value can be updated while key cannot be changed.

  • Dictionary is known as Associative array since the Key works as Index and they are decided by the user.

Summary#

Data types

Type

String

immutable

List

mutable

Tuple

immutable

Dictionary

mutable

Creating Python Dictionary#

Creating a dictionary is as simple as placing items inside curly braces {} separated by commas or the dict() built-in function.

An item has a key and a corresponding value that is expressed as a pair {key: value}.

The key and the value is separated by a colon :. Items are separated from each other by a comma ,.

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.

# Example: empty dictionary

d = {}; l = []; t = (); s = set(); st = ""
print(d,l,t,s,st)     # ▶ {} [] () set() 
print(type(d),type(l),type(t), type(s), type(st)) 
# ▶ <class 'dict'> <class 'list'> <class 'tuple'> <class 'set'> <class 'str'>

# dictionary with integer keys
my_dict1 = {1: 'apple', 2: 'ball'}
print(my_dict1)        # ▶ {1: 'apple', 2: 'ball'}

# dictionary with mixed keys
my_dict2 = {1:"hi", "name":666, 1.5:("yes","very much"), 9: [3, 6, 9]}
print(my_dict2)        # ▶ {1: 'hi', 'name': 666, 1.5: ('yes', 'very much'), 9: [3, 6, 9]}

# from sequence having each item as a pair
my_dict3 = dict([(1,'apple'), (2,'ball')])
print(type([(1,'apple'), (2,'ball')])) # nested list
print(my_dict3)        # ▶ {1: 'apple', 2: 'ball'}
print(len(my_dict3))   # ▶ 2
{} [] () set() 
<class 'dict'> <class 'list'> <class 'tuple'> <class 'set'> <class 'str'>
{1: 'apple', 2: 'ball'}
{1: 'hi', 'name': 666, 1.5: ('yes', 'very much'), 9: [3, 6, 9]}
<class 'list'>
{1: 'apple', 2: 'ball'}
2
dict([(1, 100), ('bar', 200)]), dict(foo=100, bar=200)
({1: 100, 'bar': 200}, {'foo': 100, 'bar': 200})

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.

# Example: get vs [] for retrieving elements

my_dict = {1:'Python', 2:'Java', 3:'C++', 'c': 'Gods language'}

# method: 1
print(my_dict[1])         # ▶ Python

# method: 2
print(my_dict.get('c'))   # ▶ Gods language

# Trying to access keys which doesn't exist in dictionary:
print(my_dict.get(4))     # ▶ None

print(my_dict[4])         # ▶ KeyError!
Python
Gods language
None
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[3], line 14
     11 # Trying to access keys which doesn't exist in dictionary:
     12 print(my_dict.get(4))     # ▶ None
---> 14 print(my_dict[4])         # ▶ KeyError!

KeyError: 4
  • iterate all elemnet using for loop for keys() method, keys() method return list of all keys in dictionary.

# Example:

dict = {1:'Python', 2:'Java', 3:'C++', 'c': 'Gods language'}
print(dict.keys())
for x in dict.keys():
    print(dict[x])
dict_keys([1, 2, 3, 'c'])
Python
Java
C++
Gods language

Changing and Adding Dictionary 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.

# Example 1: Changing and adding Dictionary Elements

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

my_dict['age'] = 25   # update value
print(my_dict)        # ▶ {'age': 25, 'name': 'Arthur'}

my_dict['address'] = 'Downtown'  # add item
print(my_dict)        # ▶ {'name': 'Arthur', 'age': 25, 'address': 'Downtown'}
{'name': 'Arthur', 'age': 25}
{'name': 'Arthur', 'age': 25, 'address': 'Downtown'}
# Example 2: 

my_dict = {1:'Python', 2:'Java', 3:'C++'}
my_dict[3]="R"     # update value
my_dict[4]="PHP"   # insert new value
print(my_dict)     # ▶ {1: 'Python', 2: 'Java', 3: 'R', 4: 'PHP'}
{1: 'Python', 2: 'Java', 3: 'R', 4: 'PHP'}

Removing elements from Dictionary#

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.

# Example: Removing elements from a dictionary


squares = {1:1, 2:4, 3:9, 4:16, 5:25}   # create a dictionary

# remove a particular item, returns its value
print(squares.pop(4))    # ▶ 16
print(squares)           # ▶ {1: 1, 2: 4, 3: 9, 5: 25}

# remove an arbitrary item, return (key,value)
print(squares.popitem()) # ▶ (5, 25)
print(squares)           # ▶ {1: 1, 2: 4, 3: 9}

squares.clear()          # remove all items
print(squares)           # ▶ {}

del squares              # delete the dictionary itself
print(squares)           # ▶ NameError!!!
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-53-bb99b9cebaa8> in <module>
     16 
     17 del squares              # delete the dictionary itself
---> 18 print(squares)           # ▶ NameError!!!

NameError: name 'squares' is not defined
# Example:

my_dict = {1:'Python', 2:'Java', 3:'C++', 4:'PHP'}
del my_dict[3]    # ▶ {1: 'Python', 2: 'Java', 4: 'PHP'} ∵ remove entry with key '3'
print(my_dict)    # ▶ {}

my_dict.clear()   # remove all entries in dict
print("my_dict : ",my_dict)  # ▶ my_dict :  {}

del my_dict       # delete entire dictionary
print(my_dict[2]) # ▶ NameError!!!
{1: 'Python', 2: 'Java', 4: 'PHP'}
my_dict :  {}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[4], line 11
      8 print("my_dict : ",my_dict)  # ▶ my_dict :  {}
     10 del my_dict       # delete entire dictionary
---> 11 print(my_dict[2]) # ▶ NameError!!!

NameError: name 'my_dict' is not defined

Dictionary Built-in Dictionary Functions#

Built-in functions like all(), any(), len(), cmp(), sorted(), str(), typ(), etc. are commonly used with dictionaries to perform different tasks.

Function

Description

all()

Returns True if all keys of the dictionary are true (or if the dictionary is empty).

any()

Returns True if any key of the dictionary is true. If the dictionary is empty, return False.

len()

Returns the length (the number of items) in the dictionary.

cmp()

Compares items of two dictionaries. (Not available in Python 3).

sorted()

Returns a new sorted list of keys in the dictionary.

str()

Produces a printable string representation of a dictionary.

type()

Returns the type of the passed variable. If passed variable is dictionary,then it would return a dictionary type.

Here are some examples that use built-in functions to work with a dictionary.

# Example: Dictionary Built-in Functions

# all will give True if all "Key" is "True". 0 is also consider as False 

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

print(all(squares))     # ▶ False
print(any(squares))     # ▶ True
print(len(squares))     # ▶ 6
print(sorted(squares))  # ▶ [0, 1, 3, 5, 7, 9]
False
True
6
[0, 1, 3, 5, 7, 9]

all(dict) - The all() function returns True when all elements in the given iterable are true. If not, it returns False.#

In case of dictionaries, if all keys (not values) are true or the dictionary is empty, all() returns True. Else, it returns false for all other cases.

# Example 1: How all() works with Python dictionaries?
# In case of dictionaries, if all keys (not values) are true or the dictionary is empty, 
# all() returns True. Else, it returns false for all other cases.

my_dict = {0:'False', 1:'False'}
print(all(my_dict))   # ▶ False

my_dict = {1:'True', 2:'True'}
print(all(my_dict))   # ▶ True

my_dict = {1:'True', False:0}
print(all(my_dict))   # ▶ False

my_dict = {}
print(all(my_dict))   # ▶ True

# 0 is False
# '0' is True
my_dict = {'0':'True'}
print(all(my_dict))   # ▶ True
False
True
False
True
True

any(dict) - The any() function returns True if any element of an iterable is True. If not, any() returns False.#

In the case of dictionaries, if all keys (not values) are false or the dictionary is empty, any() returns False. If at least one key is true, any() returns True.

# Example 1: How any() works with Python dictionaries?

my_dict = {0:'False'}             
print(any(my_dict))                # ▶ False ∵ 0 is False

my_dict = {0:'False', 1:'True'}  
print(any(my_dict))                # ▶ True ∵ 1 is True

my_dict = {0:'False', False:0}   
print(any(my_dict))                # ▶ False ∵ both 0 and False are False

my_dict = {}                       
print(any(my_dict))                # ▶ False ∵ iterable is empty

# 0 is False
# '0' is True
my_dict = {'0':'False'}           
print(any(my_dict))                # ▶ True
False
True
False
False
True

len(dict) - The len() function gives the total length of the dictionary. This would be equal to the number of items in the dictionary.#

# Example:

my_dict = {1:'Python', 2:'Java', 3:'C++', 4:'PHP'}
print(len(my_dict))  # ▶ 4
4

sorted(dict) - The sorted() function sorts the elements of a given iterable in a specific order (either ascending or descending) and returns the sorted iterable as a list.#

# Example:

my_dict = {'e':1, 'a':2, 'u':3, 'o':4, 'i':5}
print(sorted(my_dict))               # ▶ ['a', 'e', 'i', 'o', 'u']
print(sorted(my_dict, reverse=True)) # ▶ ['u', 'o', 'i', 'e', 'a']
['a', 'e', 'i', 'o', 'u']
['u', 'o', 'i', 'e', 'a']

str(dict) - The str() function produces a printable string representation of a dictionary.#

# Example:

my_dict = {1:'Python', 2:'Java', 3:'C++', 4:'PHP'}
print(str(my_dict)) # ▶ {1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}
{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}

type() - The type() function returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.#

# Example:

my_dict = {1:'Python', 2:'Java', 3:'C++', 4:'PHP'}
print(type(my_dict))  # ▶ <class 'dict'>
<class 'dict'>

Python Dictionary Methods#

Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.

Method

Description

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.

Here are a few example use cases of these methods.

# Example: Dictionary Methods

marks = {}.fromkeys(['Math', 'English', 'Science'], 0)
print(marks)                        # ▶ {'English': 0, 'Math': 0, 'Science': 0}

for item in marks.items():
    print(item)

print(list(sorted(marks.keys())))   # ▶ ['English', 'Math', 'Science']
{'Math': 0, 'English': 0, 'Science': 0}
('Math', 0)
('English', 0)
('Science', 0)
['English', 'Math', 'Science']

clear() - The method clear() removes all items from the dictionary.#

# Example:

my_dict = {1:'Python', 2:'Java', 3:'C++', 4:'PHP'}

print(str(my_dict))  # ▶ {1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}
dict.clear()
print(str(my_dict))  # ▶ {}
{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}
{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}

copy() - The method copy() returns a shallow copy of the dictionary.#

# Example:

dict1 = {1:'Python', 2:'Java', 3:'C++', 4:'PHP'}
dict2 = dict1.copy()
print(dict2)  # ▶ {1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}
{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}

itmes() - The method items() returns a list of dict’s (key, value) tuple pairs.#

# Example:

my_dict = {1:'Python', 2:'Java', 3:'C++', 4:'PHP'}
print(my_dict.items()) # ▶ dict_items([(1, 'Python'), (2, 'Java'), (3, 'C++'), (4, 'PHP')])
dict_items([(1, 'Python'), (2, 'Java'), (3, 'C++'), (4, 'PHP')])

keys() - The method keys() returns a list of all the available keys in the dictionary.#

# Example:

my_dict = {1:'Python', 2:'Java', 3:'C++', 4:'PHP'}
all_keys=my_dict.keys()
print(all_keys)  # ▶ dict_keys([1, 2, 3, 4])
dict_keys([1, 2, 3, 4])

fromkeys() - The method fromkeys() creates a new dictionary with keys from seq and values set to value.#

Syntax:

dict.fromkeys(seq[, value])
# Example:

seq = ('Python', 'Java', 'C++')
my_dict = my_dict.fromkeys(seq)

print ("new_dict : %s" % str(my_dict)) # ▶ new_dict : {'python': None, 'java': None, 'c++': None}
my_dict = my_dict.fromkeys(seq, 50)
print ("new_dict : %s" % str(my_dict)) # ▶ new_dict : {'python': 50, 'java': 50, 'c++': 50}
new_dict : {'Python': None, 'Java': None, 'C++': None}
new_dict : {'Python': 50, 'Java': 50, 'C++': 50}

setdefault() - The method setdefault() is similar to get but will set dict[key] = default if key is not already in dict.#

Syntax:

dict.setdefault(key, default = None)
  • key −> This is the key to be searched.

  • default −> This is the Value to be returned in case key is not found.

# Example:

my_dict={'emp_name':'Milaan', 'age':96, 'emp_id':999}
my_dict.setdefault('company','JLUFE')
print(my_dict['emp_name'])   # ▶ Milaan
print(my_dict['company'])    # ▶ JLUFE
Milaan
JLUFE

update() - The method update() adds dictionary dict2’s key-values pairs in to dict. This function does not return anything.#

Syntax:

dict.update(dict2)
# Example:

dict1 = {1:'Python', 2:'Java', 3:'C++', 4:'PHP'}
dict2 = {1: 'Python3',5:'C'}  # update Python to Python3
dict1.update(dict2)
print(dict1)   # ▶ {1: 'Python3', 2: 'Java', 3: 'C++', 4: 'PHP', 5: 'C'}
{1: 'Python3', 2: 'Java', 3: 'C++', 4: 'PHP', 5: 'C'}

value() - The method values() returns a list of all the values available in a given dictionary.#

# Example:

dict1 = {1:'Python', 2:'Java', 3:'C++', 4:'PHP'}
values= dict1.values()
print(values)  # ▶ dict_values(['Python', 'Java', 'C++', 'PHP'])
dict_values(['Python', 'Java', 'C++', 'PHP'])

Python Dictionary Comprehension#

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.

# Example: Dictionary Comprehension

squares = {x: x*x for x in range(6)}
print(squares)  # ▶ {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

This code is equivalent to

# Example:

squares = {}
for x in range(6):
    squares[x] = x*x
print(squares)  # ▶ {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

A dictionary comprehension can optionally contain more for or if statements.

An optional if statement can filter out items to form the new dictionary.

Here are some examples to make a dictionary with only odd items.

# Example: Dictionary Comprehension with if conditional

odd_squares = {x: x*x for x in range(11) if x % 2 == 1}
print(odd_squares)  # ▶ {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

Other Dictionary Operations#

1. Dictionary Membership Test#

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.

# Example: Membership Test for Dictionary Keys

squares = {1: 1, 3: 9, 5: 25, 7: 99, 9: 61}

print(1 in squares)      # ▶ True

print(2 not in squares)  # ▶ True

# membership tests for key only not value
print(99 in squares)     # ▶ False
True
True
False

2. Iterating Through a Dictionary#

We can iterate through each key in a dictionary using a for loop.

# Example: Iterating through a Dictionary

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