首页 > 解决方案 > python字典获取键

问题描述

我看到有几个人说

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

是一种比其他方式更 Pythonic 的方式。为什么人们不使用 keys() 功能?

for key in dict.keys():
    print(key)

标签: python-3.xdictionary

解决方案


因为如果您只需要键,那么作为可迭代对象的 dict 对象将已经生成键:

for key in dictionary:
    print(key)

如果您需要字典的值,则使用以下items方法:

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

使代码比使用键访问 dict 值更具可读性:

for key in dictionary:
    print(key, dict[key])

keys方法的唯一实际用途是进行set基于 - 的操作,因为该keys方法返回一个类似集合的视图:

# use set intersection to obtain common keys between dict1 and dict2
for key in dict1.keys() & dict2.keys():
    print(key)

推荐阅读