根据值从字典中选择对象

时间:2016-12-28 04:12:45

标签: python dictionary

我有一本字典:

dd = {"one":"red", "two":"red", "three":"blue", "four":"yellow", "five":"blue"}

我想创建一个简单的行" if"通过并选择具有值的对象,让我们说"蓝色"。

我的尝试:

dd = {"one":"red", "two":"red", "three":"blue", "four":"yellow", "five":"blue"}
for number in dd:
     if 'blue' in dd.values():
          print("The number "+number+", likes color blue!")
     else:
          print("I'm a number that do not like color blue")



The number one, likes color blue!
The number three, likes color blue!
The number two, likes color blue!
The number five, likes color blue!
The number four, likes color blue!
>>>

它不能正常工作。

我希望只选择有价值的对象"蓝色"并为他们打印声明。

感谢您的帮助。

5 个答案:

答案 0 :(得分:1)

您可以遍历items并检查整个过程中的值,如果值为blue则打印密钥:

for k, v in dd.items():
    if v == "blue":
        print("The number " + k + ", likes color blue!")

# The number three, likes color blue!
# The number five, likes color blue!

答案 1 :(得分:0)

使用'items'方法:

dd = {"one":"red", "two":"red", "three":"blue", "four":"yellow", "five":"blue"}
for number, color in dd.items():
    if color == 'blue':
        print("The number "+number+", likes color blue!")

答案 2 :(得分:0)

@Psidom已经提供了更好的答案,但这是最小的变化答案。

dd = {"one":"red", "two":"red", "three":"blue", "four":"yellow", "five":"blue"}

for number in dd:
     if 'blue' == dd[number]:
          print("The number "+number+", likes color blue!")
     else:
          print("I'm a number that do not like color blue")

在你的代码中,你会在每次迭代中检查相同的东西,所以猜猜看是什么!它总是一样的结果。

如果您在通常用于列表的dict方法中迭代for x in y,那么您将获得dict个键作为迭代变量,因此如果您只是将其用作索引回到dict,你就得到了价值。它不如d.items()那么有效,因为它需要计算每个项目的哈希值,并且可能会散列哈希值碰撞的项目列表。

答案 3 :(得分:0)

使用发电机:

dd = {
    "one": "red",
    "two": "red",
    "three": "blue",
    "four": "yellow",
    "five": "blue"
}

for number in (k for k, v in dd.items() if v == 'blue'):
    print("The number " + number + ", likes color blue!")

答案 4 :(得分:0)

dd = {"one":"red", "two":"red", "three":"blue", "four":"yellow", "five":"blue"}

for number in dd: 
    if dd[number] == 'blue':
        print("The number "+number+", likes color blue!")
    else:
        print("I'm a number that do not like color blue")

<强>输出:

I'm a number that do not like color blue
The number three, likes color blue!
The number five, likes color blue!
I'm a number that do not like color blue
I'm a number that do not like color blue

你是if if语句给出了整个列表而不是每次只给出一个值...我只是编辑了你的if语句,其余代码是相同的......