当前位置:主页 > 软件编程 > Python代码 >

python 获取字典特定值对应的键的实现

时间:2021-05-11 08:55:26 | 栏目:Python代码 | 点击:

对于字典,通过“键”获得“值”非常简单,但通过“值”获得“键”则需绕些弯子。

一、通用:自行定义函数方式

假设:

def getKey(dic,value):
  if value not in dic:
    return None
  result=set()
  for key in dic:
    result.add(key)
  return result

二、限制:使用内置函数

假设:​​​​​需获取最大“值”对应的“键”,若dic.values()全部“值”均不相同,则可以直接使用max(dict, key)

max(dic,key=dic.get)

Python字典根据值来取键

三种方法:

s = {'a':100,'b':200,'c':300}

1.print([k for k,v in s.items() if v==200])

2.b=list(s.keys())[list(s.values()).index(200)]
#将字典的值变列表,找目标下标,将键变成列表,根据刚才的下标求得值

3.new_dict={v:k for k,v in s.items()}
print(new_dict)
print(new_dict[200])
#创建新字典,在字典中查询值,但是有时候值会重复,转为字典后只有一个

您可能感兴趣的文章:

相关文章