如何在 Python 中打印字典的键

在 Python 中打印字典的键

How to Print a dictionary’s Keys in Python

使用该dict.keys()方法打印字典的键,例如
print(list(dict.keys)). dict.keys()方法返回字典键的视图。list()如有必要,将视图传递给类以将其转换为列表。

main.py
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30 } # ✅️ print dictionary keys as view print(my_dict.keys()) # 👉️ dict_keys(['id', 'name', 'age']) # ✅️ print dictionary keys as list print(list(my_dict.keys())) # 👉️ ['id', 'name', 'age'] # ✅️ access specific key in the dictionary print(list(my_dict.keys())[0]) # 👉️ id # ✅️ print dictionary values print(my_dict.values()) # 👉️ dict_values([1, 'bobbyhadz', 30]) # ✅️ print dictionary items for key, value in my_dict.items(): # id 1 # name bobbyhadz # age 30 print(key, value)

我们使用该dict.keys()方法来打印字典的键。

dict.keys方法返回字典键的
新视图。

main.py
my_dict = {'id': 1, 'name': 'BobbyHadz'} print(my_dict.keys()) # 👉️ dict_keys(['id', 'name'])

您经常需要做的事情是将键的视图转换为列表。

main.py
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30 } keys = list(my_dict.keys()) print(keys) # 👉️ ['id', 'name', 'age'] print(keys[0]) # 👉️ id print(keys[2]) # 👉️ age
键按插入顺序存储,因此您可以使用索引一致地访问它们。

If you need to print the dictionary’s values, use the dict.values() method.

main.py
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30 } print(my_dict.values()) # 👉️ dict_values([1, 'bobbyhadz', 30]) values = list(my_dict.values()) print(values) # 👉️ [1, 'bobbyhadz', 30] print(values[0]) # 👉️ 1 print(values[1]) # 👉️ bobbyhadz

The dict.values
method returns a new view of the dictionary’s values.

There is also a dict.items() method that is often used to iterate over the
dictionary’s items.

main.py
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30 } # 👇️ [('id', 1), ('name', 'bobbyhadz'), ('age', 30)] print(list(my_dict.items())) for key, value in my_dict.items(): # id 1 # name bobbyhadz # age 30 print(key, value)

The dict.items
method returns a new view of the dictionary’s items ((key, value) pairs).

If you need to print a dictionary key by value, use the dict.keys() and dict.values() methods.
main.py
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30 } key = list(my_dict.keys())[list(my_dict.values()).index('bobbyhadz')] print(key) # 👉️ name

We used the list.index() method to get the index of the value bobbyhadz in
the dictionary and accessed the list of keys at the index.

We had to convert the view object of keys to a list because view objects are not
subscriptable (don’t allow index access).

我们还必须将视图对象转换为列表才能使用该
list.index()方法。

list.index()方法返回其值等于提供的参数的第一个项目的索引。