A dictionary in Python is a collection that stores data in the form of key–value pairs. It is declared using curly braces { } .
Python
student = { "name": "Ram", "age": 21, "course": "B.Tech" } Features :
Key Value pair - Each Value is stored as key value pair
Key Must be Unique
Mutable
Keys must be Immutable
Unordered
Accessing Dictionary Items :
Using Keys :
Python
student = { "name": "Ram", "age": 21, "course": "B.Tech" } print(student['name']) #output Ram get() method :
Python
student = { "name": "Ram", "age": 21, "course": "B.Tech" } print(student.get("age")) #output 21 keys() method :
Returns all the keys
Python
student = { "name": "Ram", "age": 21, "course": "B.Tech" } print(student.keys()) #output dict_keys(['name', 'age', 'course']) values() method :
Returns all the values
Python
student = { "name": "Ram", "age": 21, "course": "B.Tech" } print(student.values()) #output dict_values(['Rahul', 21, 'B.Tech']) items() method :
Returns the key and values together
Python
student = { "name": "Ram", "age": 21, "course": "B.Tech" } print(student.items()) #output dict_items([('name', 'Rahul'), ('age', 21), ('course', 'B.Tech')]) Using Loops :
Python
student = { "name": "Ram", "age": 21, "course": "B.Tech" } for k in student: print(k) #output name age course