Python字典的键和值

3
我有一个叫做“humans”的字典。我想遍历该字典,如果值小于20,则打印出字典的键。
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}
4个回答

5

你提出的问题描述几乎是实现该功能的伪代码:

# 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.

3

试试这个:

for k, v in humans.items():
   if v > 20:
      print(k)

或者,更符合Python风格的方式是:
print([k for k, v in humans.items() if v > 20])

3

尝试使用生成器表达式,如下:

result = (k for k, v in humans.items() if v > 20)
print(', '.join(result))

如果你需要将每个项目分别放在不同的行中,我使用逗号作为分隔符,请用 '\n' 替换 ', '

1
只需要添加一个打印语句,就可以了 ;) - Óscar López

3

循环遍历items()

您可以使用推导式(无需使用[ ],因为它已经在括号中了):

print(k for k,v in humans.items() if v > 20)

或者真正的循环:
for k,v in humans.items():
    if v > 20:
       print(k)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接