How is the python dictionary function used?
In Python, a dictionary is a mutable container model that can store any number of key-value pairs. Each element in the dictionary is made up of a key and a value separated by a colon (:), with each key-value pair separated by a comma (,) and the entire dictionary wrapped in curly braces ({}).
Some common methods of using a dictionary include:
- dict.keys(): This method returns all the keys in the dictionary.
- Return all values in the dictionary.
- Return all key-value pairs in the dictionary.
- dict.get(key, default): Retrieve the value corresponding to a key, returning the default value if the key does not exist.
- Update the key-value pairs from another dictionary into the current dictionary.
- dict.pop(key): Remove the specified key and its corresponding value.
- Clear all key-value pairs from the dictionary using dict.clear().
For example:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(my_dict.keys()) # 输出: dict_keys(['name', 'age', 'city'])
print(my_dict.values()) # 输出: dict_values(['Alice', 30, 'New York'])
print(my_dict.items()) # 输出: dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])
print(my_dict.get('name', 'Unknown')) # 输出: Alice
my_dict.update({'gender': 'Female'})
print(my_dict) # 输出: {'name': 'Alice', 'age': 30, 'city': 'New York', 'gender': 'Female'}
my_dict.pop('age')
print(my_dict) # 输出: {'name': 'Alice', 'city': 'New York', 'gender': 'Female'}
my_dict.clear()
print(my_dict) # 输出: {}