Dictionaries are unordered collections of key-value pairs. They are used to store data in an associative manner.
Creating Dictionaries
Python
# Empty dictionary
empty_dict = {}
# Dictionary with elements
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
Accessing Dictionary Elements
You can access values in a dictionary using their corresponding keys.
Python
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(person['name']) # Output: Alice
Adding and Modifying Elements
Dictionaries are mutable, allowing you to add or modify key-value pairs.
Python
person['occupation'] = 'engineer' # Add a new key-value pair
person['age'] = 31 # Modify an existing value
Key Points
- Keys in a dictionary must be unique and immutable (strings, numbers, or tuples).
- Dictionaries are unordered, meaning the order of elements is not guaranteed.
- You can use the
in
andnot in
operators to check if a key exists in a dictionary.
How do you create a dictionary?
Use curly braces {}
to create a dictionary.
How do you access a value in a dictionary?
Use the key to access the corresponding value.
Can you modify values in a dictionary?
Yes, you can modify values by assigning new values to existing keys.
How do you add a new key-value pair to a dictionary?
Assign a value to a new key.
How do you remove a key-value pair from a dictionary?
Use the del
keyword or the pop()
method.
Can a dictionary contain duplicate keys?
No, dictionary keys must be unique.
Can a dictionary contain mutable objects as keys?
No, dictionary keys must be immutable.
Can you create dictionaries using comprehensions?
Yes, you can use dictionary comprehensions to create dictionaries concisely.
When should I use a dictionary instead of a list?
Use a dictionary when you need to access data by key rather than by index.
Can a dictionary contain another dictionary?
Yes, dictionaries can be nested.
Are dictionaries ordered in Python?
In Python 3.7 and later, dictionaries maintain insertion order.
What is the time complexity of dictionary operations?
Average time complexity for most operations is O(1).