编写一个python程序,实现根据字典的值查询并返回对应的键。函数的形参有两个,一个是被查询的字典,另一个是需要查询的值构成的列表;返回值为一个新的字典,该字典中每一个元素的键为需要查询的值,该字典的值为在原字典中查询到的键。例如:已知被查询的字典为: My_dict={"西安":"029","宝鸡":"0917","渭南":"0913","咸阳":"029","铜川":"0919","汉中":"0916","安康":"0915","商洛":"0914","延安":"0911","榆林":"0912"} 查询的列表为:["029","0913","0918"] 函数的返回结果应为:{'029': ['西安', '咸阳'], '0913': ['渭南'], '0918': []}
时间: 2023-06-01 13:03:03 浏览: 71
```python
def search_dict(dic, lst):
result = {}
for value in lst:
result[value] = []
for key in dic:
if dic[key] == value:
result[value].append(key)
return result
My_dict={"西安":"029","宝鸡":"0917","渭南":"0913","咸阳":"029","铜川":"0919","汉中":"0916","安康":"0915","商洛":"0914","延安":"0911","榆林":"0912"}
lst = ["029","0913","0918"]
print(search_dict(My_dict, lst)) # 输出结果为:{'029': ['西安', '咸阳'], '0913': ['渭南'], '0918': []}
```
相关问题
使用python编写一个程序,实现根据字典的值查询并返回对应的键。函数的形参有两个,一个是被查询的字典,另一个是需要查询的值构成的列表;返回值为一个新的字典,该字典中每一个元素的键为需要查询的值,该字典的值为在原字典中查询到的键。例如:已知被查询的字典为: My_dict={"西安":"029","宝鸡":"0917","渭南":"0913","咸阳":"029","铜川":"0919","汉中":"0916","安康":"0915","商洛":"0914","延安":"0911","榆林":"0912"} 查询的列表为:["029","0913","0918"] 函数的返回结果应为:{'029': ['西安', '咸阳'], '0913': ['渭南'], '0918': []}
def find_key(dic, lst):
res = {}
for val in lst:
res[val] = []
for key in dic:
if dic[key] == val:
res[val].append(key)
return res
My_dict={"西安":"029","宝鸡":"0917","渭南":"0913","咸阳":"029","铜川":"0919","汉中":"0916","安康":"0915","商洛":"0914","延安":"0911","榆林":"0912"}
lst = ["029","0913","0918"]
print(find_key(My_dict, lst)) # {'029': ['西安', '咸阳'], '0913': ['渭南'], '0918': []}
利用python编写一个程序,实现根据字典的值查询并返回对应的键。函数的形参有两个,一个是被查询的字典,另一个是需要查询的值构成的列表;返回值为一个新的字典,该字典中每一个元素的键为需要查询的值,该字典的值为在原字典中查询到的键。例如:已知被查询的字典为: My_dict={"西安":"029","宝鸡":"0917","渭南":"0913","咸阳":"029","铜川":"0919","汉中":"0916","安康":"0915","商洛":"0914","延安":"0911","榆林":"0912"} 查询的列表为:["029","0913","0918"] 函数的返回结果应为:{'029': ['西安', '咸阳'], '0913': ['渭南'], '0918': []}
以下是利用 Python 编写的程序,实现根据字典的值查询并返回对应的键:
```python
def find_keys(my_dict, query_list):
result_dict = {}
for query in query_list:
result_dict[query] = [key for key, value in my_dict.items() if value == query]
return result_dict
My_dict = {"西安":"029","宝鸡":"0917","渭南":"0913","咸阳":"029","铜川":"0919","汉中":"0916","安康":"0915","商洛":"0914","延安":"0911","榆林":"0912"}
query_list = ["029","0913","0918"]
result_dict = find_keys(My_dict, query_list)
print(result_dict)
```
输出结果为:
```
{'029': ['西安', '咸阳'], '0913': ['渭南'], '0918': []}
```
这个程序会遍历查询列表中的每一个值,然后在原字典中查找对应的键,并将结果存储在一个新的字典中返回。如果查询的值在原字典中不存在,则对应的键的值为空列表。
阅读全文