


Khusboo Tayal
Dictionaries are one of Python’s most powerful and flexible built-in data types. Unlike lists or tuples, which store values based on index positions, dictionaries store data as key-value pairs.
In this tutorial, you’ll learn how to create, access, modify, and use dictionaries in Python with practical examples.
A dictionary is a collection of unordered, mutable, and indexed data in Python. It is written using curly braces {} and contains key-value pairs.
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
student = {
"name": "John",
"grade": "A",
"passed": True
}
employee = dict(name="Emma", position="Manager", salary=75000)
You can access values using their keys:
print(student["name"]) # Output: John print(employee["position"]) # Output: Manager
To avoid errors when a key doesn’t exist, use the get() method:
print(student.get("age", "Not specified")) # Output: Not specified
student["age"] = 20
student["grade"] = "A+"
student.pop("passed") # Removes the key 'passed'del student["grade"]
student.clear() # Empties the dictionary
for key in employee:
print(key)
for value in employee.values():
print(value)
for key, value in employee.items():
print(key, ":", value)| Method | Description |
|---|---|
| get() | Returns value for the given key |
| keys() | Returns a list of all keys |
| values() | Returns a list of all values |
| items() | Returns a list of (key, value) pairs |
| update() | Updates dictionary with new key-value pairs |
| pop() | Removes a key and returns its value |
| clear() | Removes all items from the dictionary |
person = {"name": "Lily", "age": 30}
person.update({"city": "Boston"})
print(person)
Dictionaries can contain other dictionaries.
students = {
"101": {"name": "Alex", "grade": "B"},
"102": {"name": "Maya", "grade": "A"}
}
print(students["101"]["name"]) # Output: AlexPython supports dictionary comprehension, a concise way to create dictionaries.
squares = {x: x*x for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Python dictionaries are a flexible and efficient way to store and manage key-value pairs. They are extremely useful for organizing data, making lookups, and simplifying many coding tasks.
By mastering dictionaries, you unlock the full potential of Python’s data manipulation capabilities.
Q1: Can dictionary keys be of any data type?
No. Keys must be immutable types like strings, numbers, or tuples.
Q2: Are dictionaries ordered?
Yes, as of Python 3.7+, dictionaries preserve insertion order.
Q3: Can a dictionary have duplicate keys?
No. Keys must be unique. If a duplicate key is added, the latest value will overwrite the previous one.
Subscribe to our newsletter to get the latest Python tutorials, project ideas, and updates right to your inbox.
#python #pythondictionaries #dictionarypython #keyvaluepairs #pythontutorial #pythonforbeginners #learnpython #dictionarystorage #pythondatatypes