1. Creating a Dictionary
Copy empty_dict = {}
student = { " name " : " Alice " , " age " : 22 , " grade " : " A " }
print ( empty_dict )
print ( student ) Dictionaries store data as key–value pairs and are optimized for fast lookups.
2. Accessing Dictionary Values
Copy employee = { " id " : 101 , " name " : " John " , " role " : " Developer " }
print ( employee [ " name " ]) # Output: John
print ( employee . get ( " role " )) # Output: Developer [] raises KeyError if missing
get() safely returns None by default
3. Adding and Updating Dictionary Entries
Copy profile = { " username " : " admin " }
profile [ " email " ] = " admin@example.com "
profile [ " username " ] = " administrator "
print ( profile ) Assigning a value to a key adds or updates it.
4. Removing Items from a Dictionary
Used to delete keys and retrieve values.
5. Dictionary Length and Membership
Checks existence of keys only.
6. Iterating Through Dictionaries
Supports iteration over keys, values, or both.
7. Dictionary Methods
Useful for introspection and transformation.
8. Merging Dictionaries
Introduced in Python 3.9 for clean dictionary merging.
9. Nested Dictionaries
Allows structured data modeling.
10. Dictionary Comprehension
Efficient way to generate dictionaries dynamically.
Last updated 2 months ago