dictionary¶
- dictionaries are fundamental data structures used to store collections of items in a key-value format. Unlike lists and sets, which store items in an order, dictionaries provide a flexible way to associate unique keys with their corresponding values.
- Dictionaries are enclosed in curly braces
{}
with key-value pairs separated by colons:
- Keys must be unique and immutable (strings, numbers, or tuples are common choices for keys).
- Values can be of any data type (strings, integers, lists, or even other dictionaries).
- You can access a value by its associated key within square brackets
- If the key doesn't exist, a
KeyError
is raised. - Adding or Removing Elements
- Dictionaries are mutable, allowing you to modify their contents after creation
my_dict[key]
= value: Add a new key-value pair or modify an existing value for a key.del my_dict[key]
: Remove the key-value pair associated with a specific key.
- Dictionaries are mutable, allowing you to modify their contents after creation
- Common Dictionary Methods
len(my_dict)
: Returns the number of key-value pairs in the dictionary.get(key, default)
: Returns the value for a key, or a default value if the key is not found.keys()
: Returns a view of all the keys in the dictionary as a dictionary view object.values()
: Returns a view of all the values in the dictionary as a dictionary view object.items()
: Returns a view of all the key-value pairs in the dictionary as a dictionary view object (tuples of (key, value)).pop(key, default)
: Removes the key-value pair for a key and returns the value. If the key is not found, it returns the default value (if provided).popitem()
: Removes and returns an arbitrary key-value pair from the dictionary.
- When to Use Dictionaries
- Use dictionaries when you need to associate data with unique identifiers or labels.
- They are well-suited for storing configuration settings, user preferences, or any data where you need to retrieve information based on a key.
- Dictionaries are essential for building more complex data structures and relationships between data elements in your programs.
- Key Points
- Dictionaries provide a flexible way to store key-value pairs.
- Keys must be unique and immutable.
- Values can be of any data type.
- Use methods to add, remove, access elements, and iterate over keys, values, or key-value pairs.
In [ ]:
Copied!
fruits = {"apple": "red", "banana": "yellow", "cherry": "red"}
apple_color = fruits["apple"] # apple_color will be "red"
fruits = {"apple": "red", "banana": "yellow", "cherry": "red"}
apple_color = fruits["apple"] # apple_color will be "red"