elif循环中的python dict值

2024-06-28 06:23:33 发布

您现在位置:Python中文网/ 问答频道 /正文

每次我输入一个值,代码都会给我“subscribe”…如何获得dict值

Friends = {
    'rolf' : 'blue',
    'ronnie' : 'green',
    'barbara' : 'purple',
    'benny' : 'kaki',
    'stewart' : 'yellow',
    'mickey' : 'red'
}


def greetagain():

    friend = input("Enter your friend name or color? ")
    i = Friends.values()

    if friend in Friends.keys():
        print('yes it matches')
    elif i in Friends.values():
        print('ok ok')
    else:
        print('subscribe')

greetagain()

Tags: 代码infriendokgreenbluesubscribedict
2条回答

我只能理解你问题的一部分,所以,我已经尽力解释了

if条件已按原样工作。我认为您希望在elif条件中检索朋友(键)的名称,因此您可以尝试以下代码:

Friends = { 'rolf' : 'blue', 'ronnie' : 'green', 'barbara' : 'purple', 'benny' : 'kaki', 'stewart' : 'yellow', 'mickey' : 'red' }

def greetagain():
    friend = input("Enter your friend name or color? ")

    if friend in Friends.keys():
        print('Key matches')
        print("Color associted to friend is:", Friends[friend])
    elif friend in Friends.values():
        for key, value in Friends.items(): 
            if friend == value: 
                print('Color is present in list and associated by:', key)
    else:
        print('subscribe')

greetagain()

欢迎来到SO。 请注意下面的更改,您使用的变量friend没有i, 因为你可以用friend值和键进行检查

def greetagain():

    friend = input("Enter your friend name or color? ")

    if friend in Friends.keys():
        print('yes it matches')
    elif friend in Friends.values():
        print('ok ok')
    else:
        print('subscribe')

相关问题 更多 >