A Dictionary is a collection used to store data in key-value pairs. Dictionaries are ordered, changeable, and do not allow duplicate keys.
Creating a Dictionary
student = {
"name": "John",
"age": 20,
"city": "Delhi"
}
print(student)
Output:
{'name': 'John', 'age': 20, 'city': 'Delhi'}
Access Dictionary Items
You can access values using their keys.
Syntax
dictionary_name[key]
Example
student = {
"name": "John",
"age": 20
}
print(student["name"])
Output:
John
Using get()
The get() method returns the value of a specified key.
Syntax
dictionary_name.get(key)
Example
student = {
"name": "John",
"age": 20
}
print(student.get("age"))
Output:
20
Get All Keys
The keys() method returns all dictionary keys.
Example
student = {
"name": "John",
"age": 20
}
print(student.keys())
Output:
dict_keys(['name', 'age'])
Get All Values
The values() method returns all dictionary values.
Example
student = {
"name": "John",
"age": 20
}
print(student.values())
Output:
dict_values(['John', 20])
Get Key-Value Pairs
The items() method returns all key-value pairs.
Example
student = {
"name": "John",
"age": 20
}
print(student.items())
Output:
dict_items([('name', 'John'), ('age', 20)])
Check if Key Exists
Example
student = {
"name": "John",
"age": 20
}
if "name" in student:
print("Key exists")
Output:
Key exists
Dictionary Length
Example
student = {
"name": "John",
"age": 20,
"city": "Delhi"
}
print(len(student))
Output:
3
Loop Through a Dictionary
Example
student = {
"name": "John",
"age": 20
}
for key, value in student.items():
print(key, value)
Output:
name John
age 20
Summary
- Dictionaries store data in key-value pairs.
- Keys must be unique.
- Values can be of any data type.
- Use
[]orget()to access values. keys(),values(), anditems()are commonly used dictionary methods.- Dictionaries are mutable, so they can be modified after creation.