Dictionaries: Key-value operations and mapping
Dictionaries: Key-value Operations and Mapping A dictionary is a collection of key-value pairs. Keys are unique identifiers that correspond to specific keys...
Dictionaries: Key-value Operations and Mapping A dictionary is a collection of key-value pairs. Keys are unique identifiers that correspond to specific keys...
Dictionaries: Key-value Operations and Mapping
A dictionary is a collection of key-value pairs. Keys are unique identifiers that correspond to specific keys in the dictionary, while values are the associated data.
Key-Value Operations:
Getting a value by key: We can access a value associated with a specific key using the square bracket notation with the key as the index. For example, dictionary['name'] retrieves the name associated with the key 'name'.
Setting a new value for a key: We can update the value associated with a key by using the square bracket notation with the key as the index and the new value as the value. For example, dictionary['age'] = 30 sets the age associated with the key 'age' to 30.
Removing a key: We can remove a key-value pair from a dictionary by using the square bracket notation with the key as the index. For example, del dictionary['city'] removes the 'city' key from the dictionary.
Mapping:
dict() function to convert a list of tuples into a dictionary. Each tuple in the list should be in the format (key, value), where key and value are strings. For example:python
data = [(1, 'John'), (2, 'Mary'), (3, 'Bob')]
dictionary = dict(data)
zip() function to iterate over two lists simultaneously and create a new list based on the corresponding values. For example:python
age_values = [25, 32, 40]
names = ['John', 'Mary', 'Bob']
mapped_list = zip(age_values, names)
Benefits of Dictionaries:
Data organization: Dictionaries allow us to organize data based on key values, making it easier to retrieve and manipulate.
Code readability and maintainability: Using dictionaries can improve code readability and maintainability by separating data from the logic.
Efficient operations: Dictionaries provide efficient access to data, as we can retrieve values by key in constant time