简体   繁体   English

获取具有匹配值的两个字典的键

[英]Get keys of two dictionaries with matching values

I want to compare two dictionaries by looking for equivalent keys, or rather the keys that have the same values, using python. 我想通过使用python查找等效键或具有相同值的键来比较两个字典。 There are two things I'm trying to do/find: 我想做/发现两件事:

  1. The keys from both dictionaries with the same values, and 两个字典中的键具有相同的值,以及
  2. The keys that don't have an equivalent key in the other dictionary. 在另一个字典中没有等效键的键。

My Dictionaries look something like this: 我的字典看起来像这样:

dict_1={
'3471': ['AY219713', 'AJ504663'], '3460': ['AJ621556', 'AJ575744'], '0': ['AM158981', 'AM158980', 'AM158982', 'AM158979', 'AY594216', 'AY594215', 'EU053207', 'AM392286', 'L26168', 'L37584']}

dict_2 = {'478': ['AY219713', 'AJ504663'], '43': ['AJ575744', 'AJ621556'], '2321': ['AM158979', 'L37584', 'AM158982', 'EU053207', 'AY594215', 'AM392286', 'AY594216', 'L26168', 'AM158981', 'AM158980', 'CP000758', 'AY776289', 'AJ242581', 'AM422370', 'U70978', 'AY457038', 'FR668302', 'AM422371', 'AM490632', 'AM490617', 'AJ242584']}

So I want to try and get output that looks something like this, 所以我想尝试获得看起来像这样的输出,

Matching keys from Dictionary 1 and Dictionary 2:
3471 = 478, 2 values in common
3460 = 43, 2 values in common

Keys with no equal match:
Dictionary 1 = 0, etc.
Dictionary 2 = 2321, etc.

Common keys with different values don't matter. 具有不同值的通用键无关紧要。

Here is a slight variation on aj8uppal's answer - this is a little cleaner about what it calls as a match and non-match, and I think the result is closer to what you were asking for. 这是对aj8uppal答案的一个细微变化-这将其称为匹配和不匹配的内容更为清晰,我认为结果更接近您的要求。 Admit it was in part inspired by aj8uppal; 承认它部分地受到了aj8uppal的启发; note I shortened dict_1 and dict_2 for readability, and I only sort them once (important when you have 5000 keys...): 请注意,我缩短了dict_1dict_2的可读性,并且只对它们进行了一次排序(当您有5000个键时很重要...):

dict_1 = {
'3471': ['AY219713', 'AJ504663'],
'3460': ['AJ621556', 'AJ575744'],
'0': ['AM158981', 'AM158980', 'AM158982']}

dict_2 = {
'478': ['AY219713', 'AJ504663'],
'43': ['AJ575744', 'AJ621556'],
'2321': ['AM158979', 'L37584', 'AM158982']}

match1 = {}
match2 = {}
# sort once: makes a difference when you have lots of elements
for k in dict_1:
  dict_1[k] = sorted(dict_1[k])
for j in dict_2:
  dict_2[j] = sorted(dict_2[j])
for k in dict_1:
  for j in dict_2:
    if (dict_1[k] == dict_2[j]):
      match1[k]=1
      match2[j]=1
      break;

print "matching keys:"
print list(match1)
print list(match2)
print "\nnon matching keys:"
print list(set(dict_1.keys()) - set(match1))
print list(set(dict_2.keys()) - set(match2))

This gives the following output: 这给出以下输出:

matching keys:
['3471', '3460']
['478', '43']

non matching keys:
['0']
['2321']

Use the following code: 使用以下代码:

dict_1={
'3471': ['AY219713', 'AJ504663'], '3460': ['AJ621556', 'AJ575744'], '0': ['AM158981', 'AM158980', 'AM158982', 'AM158979', 'AY594216', 'AY594215', 'EU053207', 'AM392286', 'L26168', 'L37584']}

dict_2 = {'478': ['AY219713', 'AJ504663'], '43': ['AJ575744', 'AJ621556'], '2321': ['AM158979', 'L37584', 'AM158982', 'EU053207', 'AY594215', 'AM392286', 'AY594216', 'L26168', 'AM158981', 'AM158980', 'CP000758', 'AY776289', 'AJ242581', 'AM422370', 'U70978', 'AY457038', 'FR668302', 'AM42237
for k in dict_1:
    for i in dict_2:
        if sorted(dict_1[k]) == sorted(dict_2[i]):
            matches.append((k, i))

for k in matches:
    print '%s = %s' %(k[0], k[1])

This runs as: 运行方式为:

bash-3.2$ python sortkey.py
3471 = 478
3460 = 43
bash-3.2$

A bit of silly list comprehension using sets instead of sorted list 使用sets而不是sorted list的一些愚蠢的列表理解

for x in [i[0] for i in filter(None,[["%s = %s" %(key1,key2) for key1 in dict_1.keys() if set(dict_1[key1]) == set(dict_2[key2])] for key2 in dict_2.keys()])]:
    print x

This works by inverting the dictionaries and going over a set of the keys (values for the original dictionaries). 通过反转字典并遍历一组键(原始字典的值)来工作。

dict_1 = {
'3471': ['AY219713', 'AJ504663'],
'3460': ['AJ621556', 'AJ575744'],
'0': ['AM158981', 'AM158980', 'AM158982']}

dict_2 = {
'478': ['AY219713', 'AJ504663'],
'43': ['AJ575744', 'AJ621556'],
'2321': ['AM158979', 'L37584', 'AM158982']}

def compare_dicts(D1, D2):
    dict_1 = {str(sorted(v)): k for k, v in D1.iteritems()}
    dict_2 = {str(sorted(v)): k for k, v in D2.iteritems()}
    KEYS  = set(dict_1.keys() + dict_2.keys())
    both = []
    just = {0:[], 1:[]}
    for k in KEYS:
        Vals = dict_1.get(k, False), dict_2.get(k, False)
        if all(map(bool, Vals)):
            both.append('{} = {}'.format(*map(str, Vals)))
        else:
            i = 0 if Vals[0] else 1
            just[i].append(Vals[i])

    print 'Matching keys from Dictionary 1 and Dictionary 2:'
    print '\n'.join(both)
    print
    print 'Keys with no equal match:'
    print 'Dictionary 1 = {}'.format(','.join(map(str, just[0])))
    print 'Dictionary 2 = {}'.format(','.join(map(str, just[1])))


compare_dicts(dict_1, dict_2) 

This give the desired output of 这给出了所需的输出

Matching keys from Dictionary 1 and Dictionary 2:
3460 = 43
3471 = 478

Keys with no equal match:
Dictionary 1 = 0
Dictionary 2 = 2321

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

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