编写一个程序,实现根据字典的值查询并返回对应的键。函数的形参有两个,一个是被查询的字典,另一个是需要查询的值构成的列表;返回值为一个新的字典,该字典中每一个元素的键为需要查询的值,该字典的值为在原字典中查询到的键。例如:已知被查询的字典为: My_dict={"西安":"029","宝鸡":"0917","渭南":"0913","咸阳":"029","铜川":"0919","汉中":"0916","安康":"0915","商洛":"0914","延安":"0911","榆林":"0912"} 查询的列表为:["029","0913","0918"] 函数的返回结果应为:{'029': ['西安', '咸阳'], '0913': ['渭南'], '0918': []}
时间: 2023-06-01 07:03:02 浏览: 88
python 获取字典特定值对应的键的实现
def find_key(dic, lst):
res = {}
for val in lst:
res[val] = [k for k, v in dic.items() if v == val]
return res
My_dict = {"西安":"029","宝鸡":"0917","渭南":"0913","咸阳":"029","铜川":"0919","汉中":"0916","安康":"0915","商洛":"0914","延安":"0911","榆林":"0912"}
query_lst = ["029","0913","0918"]
result = find_key(My_dict, query_lst)
print(result) # {'029': ['西安', '咸阳'], '0913': ['渭南'], '0918': []}
阅读全文