我目前有下面的代码可以正常工作:
有人可以帮我解决由字典中具有相同编号的两个键引起的冲突吗?
我尝试了多种方法(此处未列出)来尝试创建一个数组来处理它,但是我的方法仍然不成功。
我正在使用#python3.7
def find_key(dic1, n):
'''
Return the key '3' from the dict
below.
'''
d = {}
for x, y in dic1.items():
# swap keys and values
# and update the result to 'd'
d[y] = x
try:
if n in d:
return d[y]
except Exception as e:
return (e)
dic1 = {'james':2,'david':3}
# Case to test that return ‘collision’
# comment 'dic1' above and replace it by
# dic1 below to create a 'collision'
# dic1 = {'james':2,'david':3, 'sandra':3}
n = 3
print(find_key(dic1,n))
任何帮助将不胜感激。
您知道应该有多次退货,所以请提前计划。
def find_keys_for_value(d, value):
for k, v in d.items():
if v == value:
yield k
data = {'james': 2, 'david': 3, 'sandra':3}
for result in find_keys_for_value(data, 3):
print (result)