Dictionary in Python
Python tutorial · PySpark.in
Dictionary
A Dictionary in Python is a powerful data structure used to store data in key–value pairs.
- Keys must be unique
- Values can be anything
- Ordered (after Python 3.7)
- Mutable (you can add, update, delete)
Syntax :
1. Creating a Dictionary
A dictionary is created using curly braces {} with key:value pairs.
2. Accessing Values
You can access values using keys, not indexes.
Using .get() (safer Method)
If the key does not exist, .get() returns None instead of an error.
3. Changing Values
Updating the value of an existing key in the dictionary.
4. Adding New Key–Value Pair
Creating a new entry in the dictionary using a new key.
5. Removing Items from a Dictionary
pop(key) → Removes a specific key and its value from the dictionary.
popitem → Removes the last inserted key–value pair
remove last inserted key
delete using del
Deletes a specific key or the entire dictionary.
clear all
Removes all key–value pairs, leaving the dictionary empty.
6. Dictionary Methods
Keys()->get all Keys
values()->get all values
items()-> get both keys & values
7. Looping Through a Dictionary
Loop keys
Iterating over all keys in the dictionary using a loop.
Loop values
Iterating over all values in the dictionary using a loop.
Loop both
Iterating using both key and value together via items()
8. Dictionary with Different Data Types
A dictionary can store values of different data types including lists, numbers, booleans, and other dictionaries.
9. Nested Dictionary
A dictionary inside another dictionary used to store structured data.
10. Length of Dictionary
The len() function returns the total number of key–value pairs.
11. Update Method
Updates existing keys or adds new key–value pairs to the dictionary.
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges