Introduction to Python Dictionaries

python dictionaries
10 November 2024

One of the very common data structures in Python is dictionaries. These structures allow you to store data in the form of keys and values. To put it simply, dictionaries are like lists, providing the ability to store collections of items, but with the distinction that each item has a unique key associated with it that can be used to access the value.

Using a dictionary is usually simpler when you want to store data related to specific characteristics. For example, if we want to store information about a person including their name, age, and job, using a dictionary instead of a list will help clarify the links between keys and values, making data access easier.

Dictionaries in Python are mutable, meaning items can be added, removed, or modified. The same flexibility applies to their ability to add, delete, or change entries. This capability allows them to store datasets that need changes dynamically.

In coding with dictionaries, you must remember that keys should be immutable, like strings and numbers, but values can be of any type.

Sample Dictionary Code in Python


dictionary = {"name": "Ali", "age": 25, "job": "engineer"}
print(dictionary["name"])  # Output: Ali
dictionary["age"] = 26  # Change age to 26
print(dictionary["age"])  # Output: 26
dictionary["location"] = "Tehran"
print(dictionary)  # Output: {"name": "Ali", "age": 26, "job": "engineer", "location": "Tehran"}
    

Line by Line Explanation

dictionary = {"name": "Ali", "age": 25, "job": "engineer"}
In this line, a new dictionary containing information about a person with keys "name", "age", and "job" is created.
print(dictionary["name"])
Using this statement, the value associated with the key "name" in the dictionary is displayed.
dictionary["age"] = 26
In this line, the value of the key "age" is changed to 26.
print(dictionary["age"])
Again, this statement displays the updated value for the key "age".
dictionary["location"] = "Tehran"
In this line, a new item with the key "location" and the value "Tehran" is added to the dictionary.
print(dictionary)
In the end, the complete content of the dictionary is displayed, which includes all previous and new keys and values.

FAQ

?

How can I create a new dictionary in Python?

?

Can I change the values in a dictionary?

?

Can dictionary keys be of list type?

?

How do I add a new element to a dictionary?