22.4 C
New York
Thursday, November 21, 2024
HomeProgrammingPythonDictionary In Python 3 | Learn With Examples

Dictionary In Python 3 | Learn With Examples

Here you will learn all about dictionary in Python 3 from how to define a dictionary to reading data an other basic operations.

The data structures you choose in your Python code make a big difference in decreasing code complexity and improving performance.

Besides 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. We will also cover how to create dictionaries, traverse data, and other basic operations.

What is a dictionary in Python 3?

The dictionary is a data structure in Python 3, just like lists. It stores data when there is an association between the data or 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 compared to tuples. In Python dictionaries, the data is stored as key and value pairs, i.e., for each key, there are associated values.

A 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 Dictionaries 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 integers, strings, or mixed data as keys.

Do note that string keys are case-sensitive.

You can use the following ways to access the elements inside a dictionary.

1. Using dictionary keys.

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

print(students4['Name'])

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

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 the student4 dictionary by using this statement students4['Name'] = 'CodeItBro'.

If the key is available in the dictionary, the value is updated. If the key is unavailable, a new key-value pair is added to 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 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, it inserts it with a value.
pop() The pop() dictionary method deletes an element with a specified key.
fromkeys() This method allows you to 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.
Himanshu Tyagi
Himanshu Tyagi
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator. With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
RELATED ARTICLES
0
Would love your thoughts, please comment.x
()
x