【发布时间】:2019-02-05 22:40:00
【问题描述】:
我有一本叫做人类的字典。我想遍历那个字典,如果值小于 20 打印字典键。
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}
【问题讨论】:
标签: python python-3.x dictionary
我有一本叫做人类的字典。我想遍历那个字典,如果值小于 20 打印字典键。
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}
【问题讨论】:
标签: python python-3.x dictionary
? 你好约翰,欢迎来到 Stack Overflow。您对问题的描述几乎是您将如何实现该问题的完美伪代码:
# I've got dictionary called humans.
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}
for key, value in humans.items(): # I want to loop through that dictionary
if value < 20: # and if value is less than 20
print(key) # print dictionary key.
【讨论】:
循环遍历items()。
您可以使用理解(无需使用[ ],因为它已经在括号中):
print(k for k,v in humans.items() if v > 20)
或真的循环:
for k,v in humans.items():
if v > 20:
print(k)
【讨论】:
试试这个,使用生成器表达式:
result = (k for k, v in humans.items() if v > 20)
print(', '.join(result))
我使用逗号作为分隔符,如果您需要将每个项目放在不同的行中,只需将 ', ' 替换为 '\n'。
【讨论】:
试试这个:
for k, v in humans.items():
if v > 20:
print(k)
或者,一种更 Pythonic 的方式:
print([k for k, v in humans.items() if v > 20])
【讨论】: