在 python3 中处理字典冲突

Handle dictionary collision in python3

我目前可以正常使用以下代码:

谁能帮我解决字典中有两个相同编号的键造成的冲突?

我尝试了多种方法(此处未列出)来尝试创建一个数组来处理它,但我的方法仍然不成功。

我正在使用#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))

如有任何帮助,我们将不胜感激。

您知道应该有多个 returns,所以请提前计划。

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)

您可以使用 defaultdict:

from collections import defaultdict

def find_key(dct, n):
    dd = defaultdict(list)
    for x, y in dct.items():
        dd[y].append(x)
    return dd[n]

dic1 = {'james':2, 'david':3, 'sandra':3}
print(find_key(dic1, 3))
print(find_key(dic1, 2))
print(find_key(dic1, 1))

输出:

['david', 'sandra']
['james']
[]

不过,只有在给定不同值的情况下重复搜索同一字典的键时,才可以从所有键和值构建默认字典。否则,肯尼奥斯特罗姆的方法更可取。无论如何,如果保持现状,以上内容毫无意义。

如果您对生成器和 yield 不放心,这里是 Kenny Ostrom 转换为列表的方法(效率低于生成器,但比上面的一次性搜索更好):

def find_key(dct, n):
    return [x for x, y in dct.items() if y == n]

输出同上