简体   繁体   English

Python Dictionary使用Lists作为值,查找具有相同值的其他键

[英]Python Dictionary using Lists as Values, find other Keys with same values

Say I have the following dictionary. 说我有以下字典。

>> sample_dict = {"1": ['a','b','c'], "2": ['d','e','f'], "3": ['g','h','a']}

I would like to find a way that would look at the values of each of the keys and return whether or not the value lists have the a duplicate variable inside. 我想找到一种方法来查看每个键的值,并返回值列表中是否有重复的变量。

For example it would output: 例如,它会输出:

>> [["1","3"] , ['a']]

I've looked at a few of the posts here and tried to use and/or change them to accomplish this, however none of what I have found has worked as intended. 我已经查看了这里的一些帖子并尝试使用和/或更改它们来实现这一点,但是我找到的所有帖子都没有按预期工作。 They would work if it was as follows: 如果它如下,它们将起作用:

>> sample_dict = {"1": ['a','b','c'], "2": ['d','e','f'], "3": ['a','b','c']}

but not if only a single value within the list was the same. 但如果列表中只有一个值相同,则不会。

You could use another dictionary to map the values to the lists of corresponding keys. 您可以使用另一个字典将值映射到相应键的列表。 Then just select the values that map to more than one key, eg: 然后只需选择映射到多个键的值,例如:

from collections import defaultdict

sample_dict = {'1': ['a','b','c'], '2': ['d','e','f'], '3': ['g','h','a']}    

d = defaultdict(list)  # automatically initialize every value to a list()

for k, v in sample_dict.items():
    for x in v:
        d[x].append(k)

for k, v in d.items():
    if len(v) > 1:
        print([v, k])

Output: 输出:

[['1', '3'], 'a']

If the list elements are hashable, you can use .setdefault to build an inverse mapping like so: 如果列表元素是可.setdefault ,则可以使用.setdefault构建反向映射,如下所示:

>>> sample_dict = {"1": ['a','b','c'], "2": ['d','e','f'], "3": ['g','h','a']}
>>> aux = {}
>>> for k, v in sample_dict.items():
...     for i in v:
...         aux.setdefault(i, []).append(k)
... 
>>> [[v, k] for k, v in aux.items() if len(v) > 1]
[[['1', '3'], 'a']]

Dictionaries map from keys to values, not from values to keys. 字典从键映射到值,而不是从值映射到键。 But you can write a function for one-off calculations. 但是你可以编写一次性计算函数。 This will incur O( n ) time complexity and is not recommended for larger dictionaries: 这将导致O( n )时间复杂度,不建议用于较大的词典:

def find_keys(d, val):
    return [k for k, v in d.items() if val in v]

res = find_keys(sample_dict, 'a')  # ['1', '3']

If you do this often, I recommend you "invert" your dictionary via collections.defaultdict : 如果你经常这样做,我建议你通过collections.defaultdict “反转”你的字典:

from collections import defaultdict

dd = defaultdict(list)

for k, v in sample_dict.items():
    for w in v:
        dd[w].append(k)

print(dd)

defaultdict(<class 'list'>, {'a': ['1', '3'], 'b': ['1'], 'c': ['1'], 'd': ['2'],
                             'e': ['2'], 'f': ['2'], 'g': ['3'], 'h': ['3']})

This costs O( n ) for the inversion, as well as additional memory, but now allows you to access the keys associated with an input value in O(1) time, eg dd['a'] will return ['1', '3'] . 这会导致反转的O( n )以及额外的内存,但现在允许您在O(1)时间内访问与输入值相关联的键,例如dd['a']将返回['1', '3']

You can use defaultdict from collections module to do this 您可以使用collections模块中的defaultdict来执行此操作

for example, 例如,

from collections import defaultdict
sample_dict = {"1": ['a','b','c'], "2": ['d','e','f'], "3": ['g','h','a']}

d = defaultdict(list)
for keys, vals in sample_dict.items():
    for v in vals:
        d[v].append(keys)


print(d)

d will return a dict , where the keys will be the values that are repeated and values will be the list in which they were repeated in d将返回一个dict ,其中键将是重复的值,值将是重复它们的列表

The output of above code is defaultdict(list,{'a': ['1', '3'],'b': ['1'],'c': ['1'],'d': ['2'],'e': ['2'],'f': ['2'],'g': ['3'],'h': ['3']}) 上面代码的输出是defaultdict(list,{'a': ['1', '3'],'b': ['1'],'c': ['1'],'d': ['2'],'e': ['2'],'f': ['2'],'g': ['3'],'h': ['3']})

Although it IS possible to get form in which you desired the output to be in, but it is not generally recommended because we are trying to get what character get repeated in which list, that feels like a job of a dictionary 虽然可以获得您希望输出的格式,但通常不推荐使用,因为我们试图让哪个字符在哪个列表中重复,这感觉就像字典的工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM