Lesson 32 of 70 – Python Dictionaries
46%

Python Dictionaries

A dictionary is a collection in Python that stores data in key-value pairs. Dictionaries are useful when you want to store and retrieve values using meaningful keys.

Note: Dictionaries are written using curly braces { }. Each item contains a key and its corresponding value separated by a colon :.
1. What is a Dictionary?

A dictionary stores information in the form of key-value pairs.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

print(student)
Output:
{'name': 'Amit', 'age': 20, 'course': 'Python'}
2. Key-Value Pair

Each dictionary item has two parts:

  • Key – identifies the value.
  • Value – stores the actual data.
student = {
    "name": "Rahul",
    "age": 21
}

Here, name and age are keys, while Rahul and 21 are their values.

3. Creating a Dictionary
person = {
    "name": "Priya",
    "city": "Patna",
    "age": 22
}

print(person)
Output:
{'name': 'Priya', 'city': 'Patna', 'age': 22}
4. Empty Dictionary

An empty dictionary can be created using curly braces.

student = {}

print(student)
Output:
{}

The type() function confirms that it is a dictionary.

student = {}

print(type(student))
Output:
<class 'dict'>
5. Accessing Dictionary Values

You can access a value by using its key inside square brackets.

student = {
    "name": "Amit",
    "age": 20
}

print(student["name"])
print(student["age"])
Output:
Amit
20
6. Using get() to Access Values

The get() method can also be used to retrieve a value.

student = {
    "name": "Rahul",
    "age": 21
}

print(student.get("name"))
Output:
Rahul
7. Accessing a Missing Key

Using square brackets with a key that does not exist raises a KeyError.

student = {
    "name": "Amit"
}

print(student["age"])
Result:
KeyError: 'age'

Using get() avoids this error and returns None by default.

print(student.get("age"))
Output:
None
8. Adding a New Item

You can add a new key-value pair by assigning a value to a new key.

student = {
    "name": "Amit",
    "age": 20
}

student["course"] = "Python"

print(student)
Output:
{'name': 'Amit', 'age': 20, 'course': 'Python'}
9. Updating a Dictionary Value

If a key already exists, assigning a new value updates that value.

student = {
    "name": "Amit",
    "age": 20
}

student["age"] = 21

print(student)
Output:
{'name': 'Amit', 'age': 21}
10. Dictionary Keys Must Be Unique

Dictionary keys must be unique. If the same key is written more than once, the later value replaces the earlier value.

student = {
    "name": "Amit",
    "name": "Rahul"
}

print(student)
Output:
{'name': 'Rahul'}
11. Dictionary Values Can Be Duplicated

Values in a dictionary do not have to be unique.

students = {
    "student1": "Amit",
    "student2": "Amit",
    "student3": "Rahul"
}

print(students)
Output:
{'student1': 'Amit', 'student2': 'Amit', 'student3': 'Rahul'}
12. Dictionary Length

Use the len() function to find the number of key-value pairs.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

print(len(student))
Output:
3
13. Checking Whether a Key Exists

Use the in operator to check whether a key exists.

student = {
    "name": "Amit",
    "age": 20
}

print("name" in student)
print("course" in student)
Output:
True
False
14. Checking a Key with not in
student = {
    "name": "Amit",
    "age": 20
}

print("course" not in student)
Output:
True
15. Dictionary Can Store Different Data Types

Dictionary values can contain different data types.

student = {
    "name": "Amit",
    "age": 20,
    "marks": 85.5,
    "passed": True
}

print(student)
Output:
{'name': 'Amit', 'age': 20, 'marks': 85.5, 'passed': True}
16. Dictionary with a List

A dictionary value can also be a list.

student = {
    "name": "Amit",
    "subjects": ["Python", "SQL", "HTML"]
}

print(student["subjects"])
Output:
['Python', 'SQL', 'HTML']
17. Dictionary with a Nested Dictionary

A dictionary can contain another dictionary as a value. This is called a nested dictionary.

student = {
    "name": "Amit",
    "details": {
        "age": 20,
        "city": "Patna"
    }
}

print(student["details"]["city"])
Output:
Patna
18. Looping Through a Dictionary

A for loop can be used to iterate through the keys of a dictionary.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

for key in student:
    print(key)
Output:
name
age
course
19. Looping Through Dictionary Values

Use the values() method to iterate through dictionary values.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

for value in student.values():
    print(value)
Output:
Amit
20
Python
20. Looping Through Keys and Values

Use the items() method to get both keys and values.

student = {
    "name": "Amit",
    "age": 20
}

for key, value in student.items():
    print(key, ":", value)
Output:
name : Amit
age : 20
21. Dictionary Keys

The keys() method returns a view containing the dictionary's keys.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

print(student.keys())
Output:
dict_keys(['name', 'age', 'course'])
22. Dictionary Values

The values() method returns a view containing the dictionary's values.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

print(student.values())
Output:
dict_values(['Amit', 20, 'Python'])
23. Dictionary Items

The items() method returns a view containing key-value pairs.

student = {
    "name": "Amit",
    "age": 20
}

print(student.items())
Output:
dict_items([('name', 'Amit'), ('age', 20)])
24. Dictionary del Keyword

The del keyword can be used to remove a specific key-value pair.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

del student["age"]

print(student)
Output:
{'name': 'Amit', 'course': 'Python'}
25. Key Points
  • A dictionary stores data in key-value pairs.
  • Dictionaries are written using { }.
  • Keys must be unique within a dictionary.
  • Dictionary values can be duplicated.
  • Values can be of different data types.
  • Use square brackets or get() to access values.
  • Use in to check whether a key exists.
  • Use keys() to access keys.
  • Use values() to access values.
  • Use items() to access keys and values together.
  • Dictionaries can contain lists, tuples, sets, or other dictionaries as values.
  • Dictionaries are mutable, so their contents can be changed.

🧠 Quick Quiz

Question: Which syntax is used to access a dictionary value using its key?