Python Dictionary keys() Method Guide

The keys() method of a dictionary is used to return all the keys in the dictionary. Here is an example of using the keys() method:

# 创建一个字典
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# 使用keys()方法获取所有键
keys = my_dict.keys()

# 打印所有键
for key in keys:
    print(key)

The output is:

name
age
city

You can also convert the return value of the keys() method into a list and then perform other operations. For example, you can use the list() function to convert the returned keys into a list.

# 创建一个字典
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# 转换为列表
keys_list = list(my_dict.keys())

# 打印列表
print(keys_list)

The output result is:

['name', 'age', 'city']

Note: In Python 3.x, the keys() method returns a view object instead of a list. However, you can still convert it into a list for further manipulation.

bannerAds