我有跟随dict并希望根据值列表从中获取密钥:
d = {
'Mot': [5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Dek': [0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Nas': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Ost': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Suk': [0, 0, 0, 0, 0, 0, 0, 3156, 1320, 450, 0, 0, 0],
'Tas': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250, 0, 0],
'Sat': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6551, 5000]
}
dz = [[5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
我试图采用get()方法而没有任何成功(返回此错误:不可用类型:' list&#39 ;;当我尝试使用numpy' s数组而不是返回时,同样的情况发生了:unhashable类型:' numpy.ndarray'):
tN= []
for index, element in enumerate(dz):
tN.append(dict((v,k) for k,v in dict_res.items()).get(element))
有没有办法如何从字典中检索值?
答案 0 :(得分:2)
您可以这样做:
d = {
'Mot': [5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Dek': [0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Nas': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Ost': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Suk': [0, 0, 0, 0, 0, 0, 0, 3156, 1320, 450, 0, 0, 0],
'Tas': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250, 0, 0],
'Sat': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6551, 5000]
}
dz = [[5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
keys = [key for elem in dz for key, value in d.items() if elem==value]
print(keys)
输出:
['Mot', 'Dek']
<强>更新强>
修改代码,以便获得正确的密钥顺序。如果:
dz = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6551, 5000],
[5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
输出是:
['Sat', 'Mot', 'Dek']
答案 1 :(得分:0)
Vasilis G.上面发布的解决方案很遗憾地重新排序了返回值,以便在以下情况下使用:
dz = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6551, 5000],
[5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
输出:
['Mot', 'Dek', 'Sat']
对于需要知道列表中值的真实顺序的情况,这可能是更好的选择:
keys = []
for i in dz:
keys.append(list(d.keys())[list(d.values()).index(i)])
#using list comprehension:
#keys = [list(d.keys())[list(d.values()).index(i)] for i in dz]
print(keys)
打印:
['Sat', 'Mot', 'Dek']