Thursday, September 21, 2023
HomeProgrammingPythonDictionary In Python 3 | Learn With Examples

Dictionary In Python 3 | Learn With Examples

This post was last Updated on by Himanshu Tyagi to reflect the accuracy and up-to-date information on the page.

Data structures that you choose in your Python code makes a big difference in decreasing code complexity and improve performance. Apart from lists and sets data structures in Python 3, you can also use dictionaries to organize your data for speedy lookup.

In this article, we will discuss dictionaries in Python 3. Additionally, we will also cover how to create dictionaries, traversing data, and other basic operations. 

Content Index:

Also ReadFree Python Programming Course For Absolute Beginners.

What is a dictionary in Python 3?

Dictionary is a data structure in Python 3, just like lists. It is used to store data when there is an association between the data or when there is a definite structure.

For instance, if you want to store students’ data in a Python program, then there are multiple attributes that you would like to save, such as name, class, subjects, etc.  In this case, using a dictionary is the right approach as compared to tuples.

In Python dictionaries, the data is stored as key and value pairs, i.e., for each key, there are associated values.

Few things to note about Python 3 dictionaries:

  • A key can have multiple values.
  • There can be multiple keys for multiple values.

Also ReadHow To Use Python For Browser Games Development?

How to create dictionaries in Python 3?

The simplest way to create an empty dictionary is to use the curly braces – student = {}

Interesting fact: Both Sets and Dictionary are defined using curly braces. They only get differentiated when you specify key-value pairs within the curly braces. 

There are three methods to create dictionaries in Python 3.

1. Using curly braces

students3 = {
    'Name':'Himanshu',
    'Class': 'B.tech',
    'Semester':'3',
    'Admission':'2020',  
}

2. Dict() function

students2 = dict(
    {
    'Name':'Himanshu',
    'Class': 'B.tech',
    'Semester':'3',
    'Admission':'2020',
    }
)

3. Using tuple inside the dict() method.

students4 = dict([
    ('Name','Himanshu'),
    ('Class','B.tech'),
    ('Semester','3'),
    ('Admission','2020'),
    ]
)

Accessing the data inside a dictionary

As dictionaries store data as key-value pairs, you can access dictionary elements using keys. You can use integer, strings, or mixed data as keys. Do note that, string keys are case-sensitive.

To access the elements inside a dictionary, you can use the following ways.

1. Using dictionary keys.

For instance, we want to read the name of a student stored in the students4 dictionary. To access the item, we will use its key, which is Name.

print(students4['Name'])

Do note that if you try to access the data with the name key instead of Name, then you will see a syntax error.

2. Get() method.

Another way to read dictionary data is to use the get() method.

print(len(students4))

Trying to access an item with the wrong key throws a None error. 

Updating data in a dictionary

Python dictionary is mutable; i.e., you can add new items and change their values. To update elements in a dictionary, you can use the assignment (=) operator. 

For example, you can update the Name item in student4 dictionary by using this statement students4['Name'] = 'CodeItBro'.

If the key is available in the dictionary, then the value is updated. In case the key is not available, then a new key-value pair is added in the dictionary. 

students4 = dict([
    ('Name','Himanshu'),
    ('Class','B.tech'),
    ('Semester','3'),
    ('Admission','2020'),
    ]
)

students4['Address'] = 'India'
print(students4)

Output: {‘Name’: ‘Himanshu’, ‘Class’: ‘B.tech’, ‘Semester’: ‘3’, ‘Admission’: ‘2020’, ‘Address’: ‘India’}

Deleting or removing items from a dictionary

We can use the pop() method to remove a specific item in a dictionary. You have to pass the key as an argument to this method. 

Here’s how we can remove the Name item from the students4 dictionary. 

students4.pop('Name')

print(students4)

Output: {‘Class’: ‘B.tech’, ‘Semester’: ‘3’, ‘Admission’: ‘2020’, ‘Address’: ‘USA’}

popitem() is another dictionary function that we can use to remove an item and return the deleted key-value pair. 

You can also delete all items in a dictionary using the clear() method. 

Let’s see other Python dictionary methods. 

Python 3 dictionary methods

values() Returns a list of all values in the dictionary.
setdefault() This method returns the value of a key. If that key is not
available in the dictionary, then it inserts the key with a value.
pop() The pop() dictionary method deletes an element with a specified key.
fromkeys() With this method, you can create a dictionary from a given sequence and values.
copy() Returns the shallow copy of the dictionary.
update() This method updates the dictionary with specified key-value pairs from another dictionary or iterable.
popitem() Popitem() deletes the last entered key-value pair from a dictionary.
keys() Returns the list of all keys in the dictionary.
clear() Deletes all the elements from a dictionary.
get() Returns the value of a specific key.
len() Return the length of a dictionary.

Python 3 programs

  1. Python 3 Program To Add Two Matrices.
  2. Python 3 Program to Check Armstrong Number.
  3. Python 3 Program to Calculate The Area of a Triangle.
  4. Python 3 Program To Solve A Quadratic Equation.
  5. Python 3 Program to Find the Square Root of A Number.

Himanshu Tyagi
Himanshu Tyagihttps://www.codeitbro.com/author/admin/
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator. Founder Cool SaaS Hunter. With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!
RELATED ARTICLES

Most Popular

Recent Posts

- Advertisment -