Dictionary in Python with Examples

Dictionary in Python

Hello Techies,

This blog is about “Dictionary in Python”. A Dictionary represents a group of elements in the form of a key-value pair. So in this blog, we will learn about the usage of the Dictionary in Python.

Check out my previous blog on built-in datatypes in Python.

Let’s start and check, How to use Dictionary in Python step by step.

Below are the Key Points of Dictionary in Python that we are covering in this blog.

  1. Python Dictionary(Introduction)
  2. Create Dictionary in Python
  3. Accessing Dictionary Element
  4. Add or Update Dictionary Element
  5. Delete or Remove elements from Dictionary
  6. Python Dictionary Comprehension
  7. Python Dictionary Methods
  8. Python Dictionary Functions
  9. Nested Dictionary in Python

#1. Python Dictionary(Introduction)

  • A Dictionary represents a group of elements in the form of a key-value pair.
  • Dictionary in Python is an unordered collection.
  • Dictionaries are mutable so we can modify its element.
  • The Dictionary is represented using a square bracket { }.
  • Example: data = {1: ‘test1’, 2: ‘test2’, 3: ‘test3’, 4: ‘test4’}

#2. Create Dictionary in Python

  • A dictionary is created in the form of key-value pair where keys can’t be repeated and must be immutable and values can be of any datatypes and can be duplicated.
  • Creating a dictionary is so easy that placing items in curly brackets({ }) separated by commas.
  • Also, we can create a dictionary using the built-in dict() function.
  • Keys are case sensitive, which means that if you take keys like Test1 and TEST1, the dictation will accept both keys as unique.

Syntax

dict_name = {key1:value1, key2:value2, key3:value3, ...}
dict_func = dict(key1 = value1, key2 = value2, key3 = value3)

Example

data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}
data1 = dict(key1 = 'test1', key2 = 'test2', key3 = 'test3')

Creating an Empty Dictionary

An empty dictionary can be created by simply placing curly braces { }.

Syntax: dict_name = { }

Example: data = { }

Key Rules

When writing the key in Dictionary you should follow the following rules:

  • The key should be unique.
  • The old key will be overwritten if we mention the same key again.
  • Key should be immutable type example:- integer, string or tuple.
  • We cannot use a list or dictionary as a key.

#3. Accessing Dictionary Element

We can access the value of a dictionary by referring to its key name, inside square brackets, or with the get() method.

If you use square brackets [], the KeyError will be raised if the key is not found in the dictionary. On the other side, the get() method returns None if the key is not found. So always use the get () method to access key in the dictionary which is always a good practice.

data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}
print(data['key2'])

# get() method
print(data.get('key3'))

# Trying to access key which does not present in the dictionary.
print(data['key5'])

# Trying to access key using get() method which does not present in the dictionary.

print(data.get('key5'))

#4. Add or Update Dictionary Element

Dictionaries are mutable, so we can add new items or change the value of an existing item using the assignment operator.

# change key value
data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}
data['key2'] = 'test'
print(data)

# add new key value in dictionary
data['key4'] = 'test4'
print(data)

Output

{'key1': 'test1', 'key2': 'test', 'key3': 'test3'} 
{'key1': 'test1', 'key2': 'test', 'key3': 'test3', 'key4': 'test4'}

#5. Delete or Remove elements from Dictionary

  • Using the pop() method, we can remove a specific item from the dictionary. This method removes an object with the provided key and returns the value.
  • The popitem() method can be used to remove and return arbitrary (key, value) item pairs from the dictionary.
  • clear() method to remove all elements from the dictionary.
  • We can use del keywords to manually remove individual items or entire dictionaries.
# deleting single element
data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}
del data ['key2']
print(data)

# pop() method
data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}
print(data.pop('key3'))
print(data)

# popitem() method
data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}
print(data.popitem())
print(data)

# clear() method
data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}
data.clear()
print(data)

# deleting the entire dictionary
data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}
del data
print(data)

#6. Python Dictionary Comprehension

  • Dictionary comprehension is very similar to list comprehension.
  • Dictionary comprehension is a way of converting one dictionary into another. During this conversion, items from the original dictionary can be conditionally added to the new dictionary and each item can be changed as needed.
  • The format of dictionary comprehension is: {key: value for (key, value) in iterable_object}.

Here is an example,

data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}
dict_variable = {key:value for (key,value) in data.items()}
print(dict_variable)

Output

{'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}

Interview question

Q: Python dictionary sorting in descending order based on values

#7. Python Dictionary Methods

The methods available with the Dictionary objects in Python programming are in the table below.

Method NameDescription
update()Updates dictionary with other key / value pairs
items()Return the new object of the dictionary’s items in (key, value) format.
fromkeys()Return dictionary with specified key and value
get()Returns the value of the specified key
pop()Removes the item with the key
clear()Removes all items from the dictionary
popitem()This method will remove the last inserted key-value pair
setdefault()This method will return the corresponding value if the key is in the dictionary. If the key does not exist in the dictionary insert the key, with the specified value
keys()This method will return a list of all the keys which present in the dictionary
values()This method will return a list of all the values which present in the dictionary
copy()The copy() method will return a copy of the list

Some examples of Python methods

data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}

# keys() method
print(data.keys())

# value() method
print(data.values())

# fromkeys() method
data1 = {}.fromkeys(['key1', 'key2', 'key3'], 1)
print(data1)

Output

dict_keys(['key1', 'key2', 'key3'])   
dict_values(['test1', 'test2', 'test3'])  
{'key1': 1, 'key2': 1, 'key3': 1}

#8. Python Dictionary Built-in Functions

The dictionary has built-in functions to perform different tasks.

Function NameDescription
cmp()Compare two dictionary items.
all()Return true if all keys in the dictionary are true
any()Return the True if any key in the dictionary is True. If the dictionary is empty, return False.
len()Return the length (number of items) in the dictionary.
sorted()Return the newly sorted keys in the dictionary.

Some examples of Python Functions

data = {'key1': 'test1', 'key2': 'test2', 'key3': 'test3'}

# len() method
print(len(data))

# sorted() method
print(sorted(data))

Output

3
['key1', 'key2', 'key3']  

#9. Nested Dictionary in Python

  • A dictionary within another dictionary is called a nested dictionary or nested of a dictionary.
  • Like dictionaries, it has keys and values.
  • The dictionary is accessed using a key.
  • Nested Dictionary is an unordered collection of dictionaries

Example: {‘dict1’: {‘key1′:’value1’}, ‘dict2’: {‘key2′:’value2’}}

I hope you understand the use of Dictionary in Python. Still, you have any doubts regarding Dictionary please comment below.

Check out the official site for more details on “Dictionary in Python”.

Leave a Comment