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:

  1. dict.keys(): This method returns all the keys in the dictionary.
  2. Return all values in the dictionary.
  3. Return all key-value pairs in the dictionary.
  4. dict.get(key, default): Retrieve the value corresponding to a key, returning the default value if the key does not exist.
  5. Update the key-value pairs from another dictionary into the current dictionary.
  6. dict.pop(key): Remove the specified key and its corresponding value.
  7. 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)  # 输出: {}
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds