2

我正在尝试从列表中读取并在字典中返回相应的值。请帮助我哪里出错了。谢谢

DICT = {"b": "21", "g": "54", "f": "121", "t": "1", "j": "33"}
n = ['b', 'w', 'f']

for keys in n:
    if keys in n:
        if n == DICT.keys():
            print(DICT.values())
        else:
            if keys not in n:
                print('Not Available')
4

6 回答 6

1
for key in n:
    if key in dict.keys():
        print(dict[key])

似乎这就是你想要做的

于 2013-06-12T19:22:17.763 回答
1

如果你使用非常简单get

for k in n:
    print(DICT.get(k, 'Not Available'))
于 2013-06-12T19:26:36.523 回答
0

如果您使用 get() 方法,这会容易得多:

DICT = {"b": "21", "g": "54", "f": "121", "t": "1", "j": "33"}
n = ['b', 'w', 'f']


for key in n:
    if DICT.get(key):
        print(DICT[key])
    else:
        print("Not available")

它产生了以下输出:

21
不可用
121

于 2013-06-12T19:22:44.363 回答
0

您正在迭代 n 的所有元素,但检查 n 是否是每个循环的字典的所有键,它不会是。尝试这样做:

for key in n:
    if key in DICT:
        print(DICT[key])
    else:
        print('not available')
于 2013-06-12T19:22:46.530 回答
0
>>>for keys in n:
       if keys in DICT.keys():
           print DICT[keys]
       else:
           print ('Not Available')

21
Not Available
121
于 2013-06-12T19:24:51.060 回答
0
print '\n'.join((DICT[key] for key in n if key in DICT))
于 2013-06-12T22:44:33.433 回答