Python Dictionaries Explained for Beginners | Key-Value Pairs in Python
Python Dictionaries- Store Data in Key-Value Pairs
Introduction
This is one of the most important data structures in Python and used heavily in real project, APIs and interviews.
Till now, we learned how to store multiple values using lists and tuples. But, what if you want to store data like this?
- Name - Sonu
- Age - 25
- Course - Python
Instead of remembering index positions, Python gives us a smarter way:
Dictionaries
A dictionary stores data in key-value pairs.
Think you it like a real dictionary:
- word = key
- meaning = value
Let's understand it step by step.
What is a Dictionary?
A dictionary is a collection of key-value pairs stored inside curly braces {} where every key value pair have a colon between them i.e., key: values to show which key and which value and each pair are separated by commas. It is mutable data type i.e., you can modify the values of the existing key or if the key is not present, you can add the new key value pair.
Example:
student = {
"name" : "Sonu",
"Age" : 25,
"Course" : "Python"
}
print(student)
Output:
{'name': 'Sonu', 'age':25, 'course': 'Python'}
Accessing Values
We use the key to access the value. Syntax is given below:
dictionary-name[key]
Thus to access the value for the key defined as "name" is above declared student dictionary, you will write:
print(student["name"])
Output:
Sonu
But, one can not access the key through same as it will show keyError.
In dictionary, the elements are unorder; one cannot access element as per specific order.
Adding New Data
You can add the new key-value pair by using the following syntax:
dictionary-name[key] = value
Thus to add the new key value pair where key name as city and value name as korba, you will write:
student["city"] = "korba"
print(student)
Updating Values
Suppose you want to add a new value to a key, we use the following syntax:
dictionary[key]= new value
Thus to update new value to age, we will write:
student["Age"] = 22
Removing Data
Suppose you wat to remove course from the dictionary student then use pop() method .
student.pop("Course")
It will remove the key "Course"
Using get() Method
This is safer than direct indexing to have a key.
print(student.get("name"))
Looping Through Dictionary
Suppose you want to add move than 20 key-value pair then if you follow the manual method it will consume lot of your time so, to manage it you can use loops:
for key, value in student.items():
print(key, ":", value)
Real-Life Example
Student Record System
student={
"name":"Sonu",
"roll_no": 101,
"marks": 89
}
print(f"student Name:{student["name"]}")
print(f"Marks:{student["marks"]}")
Practice Questions
- Create a dictionary of your personal details.
- Update one value
- Add a new key-value pair
- Remove one item
- Print all keys and values using loop
Comments
Post a Comment