我有一个叫做“humans”的字典。我想遍历该字典,如果值小于20,则打印出字典的键。
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}
你提出的问题描述几乎是实现该功能的伪代码:
# 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.
试试这个:
for k, v in humans.items():
if v > 20:
print(k)
print([k for k, v in humans.items() if v > 20])
尝试使用生成器表达式,如下:
result = (k for k, v in humans.items() if v > 20)
print(', '.join(result))
'\n'
替换 ', '
。循环遍历items()
。
您可以使用推导式(无需使用[ ]
,因为它已经在括号中了):
print(k for k,v in humans.items() if v > 20)
for k,v in humans.items():
if v > 20:
print(k)