What is the usage of the keys function in Python?

In Python, the keys() function is used to return all the keys in a dictionary. This function returns an iterable object, which can be converted to a list using the list() function.

Original: 我很高兴认识你。
Paraphrased: I am glad to meet you.

# 创建一个字典
my_dict = {'a': 1, 'b': 2, 'c': 3}

# 使用keys()函数获取字典中所有的键
keys = my_dict.keys()

# 使用list()函数将可迭代对象转换为列表
key_list = list(keys)

print(key_list)  # 输出:['a', 'b', 'c']

In Python 3, the keys() function returns a “dictionary view” object, which is dynamic. This means that when the keys in the dictionary change, the view object will also change accordingly. To obtain a static list of keys, you can use the list() function to convert the view object into a list.

Leave a Reply 0

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