Python Dictionaries
A dictionary in Python is a collection of key-value pairs. Each key is associated with a value, and keys must be unique within a dictionary.
1. Creating Dictionaries
You can create dictionaries using curly braces {} and specifying key-value pairs, separated by colons :.
Example:
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}2. Accessing Elements
You can access the value associated with a key using square brackets [] and the corresponding key.
Example:
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
name = person['name'] # 'Alice'3. Modifying Dictionaries
You can add new key-value pairs, modify existing values, or remove items from a dictionary.
Example:
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
person['age'] = 31
person['gender'] = 'Female'
del person['city']4. Dictionary Methods
Python dictionaries come with various methods for performing common operations such as keys(), values(), items(), get(), and more.
Example:
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
keys = person.keys()
values = person.values()
items = person.items()
age = person.get('age')Conclusion
Dictionaries are versatile data structures in Python that allow you to store and manipulate key-value pairs efficiently. Understanding how to create, access, modify, and use dictionary methods is essential for working with dictionaries effectively.