如何在Python中打印字典键(附代码)

170 阅读1分钟

Python Dictionary的项目以 key: value 对的形式呈现。它们是有序的,可修改的,并且不允许重复。要想知道一个字典有多少个项目,可以使用len()函数。

在 Python 中打印 dictionary keys

要在 Python 中打印 字典中的,使用dict.keys() 方法和**print()**函数来打印这些键。dict.key()方法返回一个视图对象,显示字典中所有键的列表

dict.key() 方法可以用来访问 dictionary 的元素,就像我们通过索引访问一个列表一样。让我们定义一个 dictionary,然后用dict.keys()print()方法来打印这些键:

dict = {
    'streaming': 'Netflix',
    'show': 'Shadow and Bone',
    'ratings': 'Good',
    'genre': 'Fantasy '
}

print(dict.keys())

输出

dict_keys(['streaming', 'show', 'ratings', 'genre'])

你就得到了 dictionary keys 的列表。

使用 dictionary.items() 方法

dictionary items()是一个内置的 Python 方法,用来获取所有的键和与这些键相关的值。我们可以在for 循环中使用 items() 方法,并打印字典的键和值。

如果你想一次打印一个键,这种方法更有用:

dict = {
    'streaming': 'Netflix',
    'show': 'Shadow and Bone',
    'ratings': 'Good',
    'genre': 'Fantasy '
}

for key, value in dict.items():
    print(key)

输出

streaming
show
ratings
genre

要打印 dictionary 的键和值,使用dict.items()print() 方法。

要打印 dictionary 的键,使用dict.key()print( ) 方法。

要打印 dictionary 的值,使用dict.values()print( ) 方法。

这些就是从 dictionary 对象中获取键和值的 Pythonic 方法。

本教程就到此为止。