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:
- A dictionary is written inside curly braces {}.
- Each element has a key and a value separated by a colon :.
- Keys must be unique and immutable (like strings, numbers, tuples).
- Values can be any type (string, list, dict, etc.).
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:
- dict["key"] → Throws an error if the key doesn’t exist.
- dict.get("key") → Returns None if the key doesn’t exist.
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'])