欢迎访问宙启技术站
智能推送

Python中的字典函数:get、keys、values、items和pop

发布时间:2023-07-08 20:54:07

Python中的字典是一种无序、可变的数据结构,通过键值对的方式存储数据。字典有一些内置函数可以用来操作字典的内容,包括get、keys、values、items和pop。

1. get函数:

get函数用于根据指定的键获取字典中相应的值。如果键存在,则返回对应的值;如果键不存在,则返回指定的默认值(默认为None)。

例如:

   person = {"name": "Alice", "age": 25, "city": "New York"}
   print(person.get("name"))  # 输出:Alice
   print(person.get("gender"))  # 输出:None
   print(person.get("gender", "Unknown"))  # 输出:Unknown
   

2. keys函数:

keys函数用于返回字典中所有键的列表。

例如:

   person = {"name": "Alice", "age": 25, "city": "New York"}
   print(person.keys())  # 输出:dict_keys(['name', 'age', 'city'])
   

3. values函数:

values函数用于返回字典中所有值的列表。

例如:

   person = {"name": "Alice", "age": 25, "city": "New York"}
   print(person.values())  # 输出:dict_values(['Alice', 25, 'New York'])
   

4. items函数:

items函数用于返回字典中所有键值对的元组列表。

例如:

   person = {"name": "Alice", "age": 25, "city": "New York"}
   print(person.items())  # 输出:dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])
   

5. pop函数:

pop函数用于根据指定的键删除字典中对应的键值对,并返回该键对应的值。如果键不存在,则可以指定一个默认值作为返回值。如果不指定默认值并且键不存在,则会抛出KeyError异常。

例如:

   person = {"name": "Alice", "age": 25, "city": "New York"}
   print(person.pop("age"))  # 输出:25
   print(person)  # 输出:{'name': 'Alice', 'city': 'New York'}
   print(person.pop("gender", "Unknown"))  # 输出:Unknown
   

通过使用这些字典函数,可以方便地获取、删除和遍历字典中的数据。这些函数在处理字典数据时非常有用,并且在实际编程中经常被使用。