Python Tutorial - Data Type Dictionary

Jinku Hu Jan 03, 2023
  1. Create a Python Dictionary
  2. get() Method to Access Elements of Python Dictionary
  3. Python Dictionary Update Elements
  4. Python Dictionary Delete Elements
  5. Methods Applicable to Python Dictionary
  6. Other Dictionary Operations
  7. Iterate Through a Dictionary
  8. Built-In Functions With Dictionary
Python Tutorial - Data Type Dictionary

In this section, you will learn the dictionary in Python. You will learn how to create a dictionary and how to add and delete elements from a dictionary.

Dictionary is a Python native data type whose data/values are key-value pairs. A dictionary contains unordered elements. A piece of data or value of the dictionary can be retrieved if you know the key.

Create a Python Dictionary

A dictionary can be created using curly braces {} with each element to be a pair containing key and value.

Python dictionary keys must be of immutable data type, and values can be of any type.

Consider the example below:

>>> x = {1:'blue', 'key':'pink'}
>>> print(type(x))
<class 'dict'>
>>> print('x[1] = ', x[1])      #using key to retrive value
x[1] =  blue
>>> print("x['key'] =", x['key']) #using key to retrive value
x['key'] = pink

A dictionary can also be initialized using the dict() method.

>>> dict({1: 'Blue', 2: 'Pink'})
{1: 'Blue', 2: 'Pink'}

get() Method to Access Elements of Python Dictionary

You can access the values of a dictionary by using keys. Keys can be used either with the index access operator as done above or with the get() method.

If the key is not found when using get() method, None will be returned instead of an error.

>>> d = dict({1: 'Blue', 2: 'Pink'})
>>> print(d[1])
Blue
>>> print(d.get(1))
Blue
>>> print(d[3])
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    d[3]
KeyError: 3
>>> print(d.get(3))
None

Python Dictionary Update Elements

Dictionary is mutable, so you can update, add, and delete elements from a dictionary. The elements of a dictionary can be updated by using the assignment operator.

When updating elements with a key that does not exist in the dictionary, a new key-value pair will be created; otherwise, the corresponding value will be updated.

>>> d = dict({1: 'Blue', 2: 'Pink'})
>>> d[1] = 'Yellow'
>>> print(d)
{1: 'Yellow', 2: 'Pink'}
>>> d[3] = 'Black'
>>> print(d)
{1: 'Yellow', 2: 'Pink', 3: 'Black'}

Python Dictionary Delete Elements

The following are some ways to delete elements from a dictionary:

  1. pop() method: It will remove and return the value of the corresponding given key.
  2. popitem() method: It will remove and return an arbitrary (key, value) from the dictionary.
  3. clear() method: It will delete all the elements from the dictionary but not the dictionary.
  4. del keyword: It can remove a particular method or the entire dictionary.

Consider the example below:

>>> d = dict({1: 'Blue', 2: 'Pink', 3:'Yellow', 4:'Red'})
>>> print(d.pop(2))
Pink
>>> print(d)
{1: 'Blue', 3: 'Yellow', 4: 'Red'}
>>> print(d.popitem())
(4, 'Red')
>>> print(d)
{1: 'Blue', 3: 'Yellow'}
>>> del d[3]
>>> print(d)
{1: 'Blue'}
>>> d.clear()
>>> print(d)
{}
>>> del d
>>> print(d)
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    print(d)
NameError: name 'd' is not defined

Methods Applicable to Python Dictionary

Consider the table below:

Method Description
clear() clear all the items from the dictionary
copy() copy a dictionary
fromkeys(seq[,v]) return a dictionary with seq elements as keys and values will be equal to v
get(key[,d]) get the value of the key, and if there is no key, d will be returned.
items() return the items of the dictionary as (key, value)
keys() return the keys of a dictionary
pop(key[,d]) remove an item corresponding to the key. If the key doesn’t exist value corresponding to d will be returned. If both d and key do not exist, an error will be raised.
popitem() It will return and remove both key and value from the dictionary.
setdefault(key[,d]) return the value of the key. If the key is not found, a new key will be created with the value d, and d will be returned.
update([other]) update the dictionary with keys and values as other.
values() return the values of a dictionary

Other Dictionary Operations

Dictionary Membership Check

The in keyword checks if an item is a member of the dictionary or not.

Note
The keys of a dictionary are used in membership checking, but not the values.
>>> d = dict({1: 'Blue', 2: 'Pink', 3:'Yellow', 4:'Red'})
>>> print(2 in d)
True
>>> print(5 in d)
False

Iterate Through a Dictionary

You can iterate through a dictionary by using for loop:

>>> d = dict({1: 'Blue', 2: 'Pink', 3:'Yellow', 4:'Red'})
>>> for i in d:
		print(i)
1
2
3
4

Built-In Functions With Dictionary

The following are some of the built-in functions that can be used with dictionaries to perform different tasks:

Functions Description
all() return True when all the keys of the dictionary are True. It also returns True when the dictionary is empty.
any() return True when any of the key of the dictionary is True. It returns False when the dictionary is empty.
cmp() compare two dictionaries
len() return the number of items in a dictionary or the dictionary’s length.
sorted() return a sorted list of keys of a dictionary.

Consider the following code:

>>> d = dict({1: 'Blue', 2: 'Pink', 3:'Yellow', 4:'Red'})
>>> print(len(d))
4
>>> print(sorted(d))
[1, 2, 3, 4]
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook