Dictionary in Python

A dictionary in Python is a built-in data type used to store data in key-value pairs. It is unordered, mutable, and indexed by keys.

Basic Concept:

Creating a Dictionary Let’s create a dictionary in Python.

Python

# Creating a dictionary
student = {
    "name": "Ashish",     # key = "name", value = "Ashish"
    "age": 29,            # key = "age", value = 29
    "course": "Python",   # key = "course", value = "Python"
    "marks": [85, 90, 92], # value can be a list too
    "eligible": True      # value can be a boolean
}

print(student)
# {'name': 'Ashish', 'age': 29, 'course': 'Python', 'marks': [85, 90, 92], 'eligible': True}

Accessing Dictionary Items Values in a dictionary can be accessed using keys. We can access dictionary values by using keys either in square brackets or by using get method.

Python

print(student["name"])     # Direct access → Ashish
print(student.get("age"))  # Using get() → 29

⚠️ Difference:

Accessing values We can print all the values in the dictionary using values() method. It returns a new object of the dictionary's values.

Python

# Creating a dictionary
student = {
    "name": "Ashish",     # key = "name", value = "Ashish"
    "age": 29,            # key = "age", value = 29
    "course": "Python",   # key = "course", value = "Python"
    "marks": [85, 90, 92], # value can be a list too
    "eligible": True      # value can be a boolean
}

print(student.values()) 
# dict_values(['Ashish', 29, 'Python', [85, 90, 92], True])

Accessing keys The keys() method in dictionary returns a new object of all the keys in the dictionary.

Python

# Creating a dictionary
student = {
    "name": "Ashish",     # key = "name", value = "Ashish"
    "age": 29,            # key = "age", value = 29
    "course": "Python",   # key = "course", value = "Python"
    "marks": [85, 90, 92], # value can be a list too
    "eligible": True      # value can be a boolean
}

print(student.keys())

Output dict_keys(['name', 'age', 'course', 'marks', 'eligible'])