Dictionaries in Python
A dictionary in Python is an unordered, mutable, and indexed collection of key-
value pairs. It is used to store data values like a map, where each key is unique and maps to a
corresponding value.
example_dict = {"name": "Devi", "roll_no": "0674"}
Use Cases:
Storing structured data (e.g., student records, configuration settings)
Fast lookup of values using keys
Representing JSON-like data
Implementing mappings and associative arrays
Key Characteristics
Key-Value Structure: Each item is a pair of a key and its associated value.
Mutable: You can add, update, or delete key-value pairs.
Unordered (until Python 3.6): The order of items is not guaranteed, though from
Python 3.7+, insertion order is preserved.
Keys Must Be Unique: Duplicate keys are not allowed.
Keys Must Be Immutable: Strings, numbers, and tuples can be keys.
Creating a Dictionary
We can create a dictionary in Python by placing a comma-separated sequence of key-value
pairs within curly braces {}, with a colon : separating each key and its associated value.
dict1 = {"NAME": "Devi", "ROLL NO": "0674", "CLASS": "I M.SC"}
dict() constructor provides a simple and direct way to create dictionaries
using keyword arguments. This method is useful for defining static key-value
pairs in a clean and readable manner.
dict2 = dict(NAME="Devi", ROLL_NO="0674")
Dictionary Operations
Syntax / Method Description
dict[key] Retrieves value for the given key
dict[key] = value Adds a new key-value pair
dict[key] = new_value Updates the value of an existing key
dict.pop(key) Removes the key-value pair
dict.get(key) Returns value or None if key doesn't exist
dict.keys(), dict.values() Returns views of keys, values, or items
len(dict) Returns number of key-value pairs
Example:
print("\t\t\t----------")
print("\t\t\tDICTIONARY")
print("\t\t\t----------")
dict1={"NAME":"devi","ROLL NO":"0674","CLASS":"I M.SC"}
print("1.Creating a dictionary")
print(dict1)
print("")
print("2.Adding a Key-pair")
dict1["DEPT"]="CS"
dict1["GRADE"]="A+"
print("After adding : ")
print(dict1)
print("")
print("3.Updating a dictionary")
dict1["NAME"]="Devi Jaishri"
print("After updating : ")
print(dict1)
print("")
print("4.removing an item by key")
dict1.pop("GRADE")
print(dict1)
print("")
print("5.Accessing a value by key")
print("Name:",dict1["NAME"])
print("")
Output:
----------
DICTIONARY
----------
1.Creating a dictionary
{'NAME': 'devi', 'ROLL NO': '0674', 'CLASS': 'I M.SC'}
2.Adding a Key-pair
After adding :
{'NAME': 'devi', 'ROLL NO': '0674', 'CLASS': 'I M.SC', 'DEPT':
'CS', 'GRADE': 'A+'}
3.Updating a dictionary
After updating :
{'NAME': 'Devi Jaishri', 'ROLL NO': '0674', 'CLASS': 'I M.SC',
'DEPT': 'CS', 'GRADE': 'A+'}
4.removing an item by key
{'NAME': 'Devi Jaishri', 'ROLL NO': '0674', 'CLASS': 'I M.SC',
'DEPT': 'CS'}
5.Accessing a value by key
Name: Devi Jaishri
Looping Through a Dictionary
for key, value in dict1.items():
print(key, ":", value)
This is useful for displaying or processing all entries.
Nested Dictionaries
Dictionaries can contain other dictionaries, allowing for hierarchical data structures.
student = {
"name": "Devi",
"details": {
"roll_no": "0674",
"dept": "CS"
}
}
Accessing nested values:
print(student["details"]["dept"]) # Output: CS