字典字典:打印至少共享两个公共键的字典

2024-04-26 18:45:01 发布

您现在位置:Python中文网/ 问答频道 /正文

d = {'g1':{'p1':1,'p2':5,'p3':11,'p4':1},
     'g2':{'p1':7,'p3':1,'p4':2,'p5':8,'p9':11},
     'g3':{'p7':7,'p8':7},
     'g4':{'p8':9,'p9':1,'p10':7,'p11':8,'p12':3},
     'g5':{'p1':4,'p13':1},
     'g6':{'p1':4,'p3':1,'p6':2,'p13':1}
    }

对于给定的字典“d”,我希望返回至少共享两个(“n”)键的子字典簇(存在于给定簇的所有子字典中)。我们不关心这些子字典的价值。在所有的字典中,至少有两个子词的交集。在


Tags: 字典p2p3p5p1g4g1g2
3条回答

我认为你应该先“颠倒”字典,然后很容易找到解决方案:

import collections
inverted = collections.defaultdict(list)

for key, items in d.items():
    for sub_key in items:
        inverted[sub_key].append(key)

for sub_key, keys in inverted.items():
    if len(keys) >= 2:
        print sub_key, keys

我希望我能正确理解你想要什么。这种方法很笨拙,恐怕效率很低。在

为了产生更有趣的输出,我添加了一个字典g6到d:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

d = {'g1':{'p1':1,'p2':5,'p3':11,'p4':1},
     'g2':{'p1':7,'p3':1,'p4':2,'p5':8,'p9':11},
     'g3':{'p7':7,'p8':7},
     'g4':{'p8':9,'p9':1,'p10':7,'p11':8,'p12':3},
     'g5':{'p1':4,'p13':1},
     'g6':{'p1':1,'p9':2,'p11':12}
    }

clusters = {}

for key, value in d.items ():
    cluster = frozenset (value.keys () )
    if cluster not in clusters: clusters [cluster] = set ()
    clusters [cluster].add (key)


for a in clusters.keys ():
    for b in clusters.keys ():
        if len (a & b) > 1 and a ^ b:
            cluster = frozenset (a & b)
            if cluster not in clusters: clusters [cluster] = set ()
            for x in clusters [a]: clusters [cluster].add (x)
            for x in clusters [b]: clusters [cluster].add (x)

print "Primitive clusters"
for key, value in filter (lambda (x, y): len (y) == 1, clusters.items () ):
    print "The dictionary %s has the keys %s" % (value.pop (), ", ".join (key) )

print "---------------------"
print "Non-primitive clusters:"
for key, value in filter (lambda (x, y): len (y) > 1, clusters.items () ):
    print "The dictionaries %s share the keys %s" % (", ".join (value), ", ".join (key) )

有点像

for keya in d:
    tempd = {}
    keys = set()
    tempset = set(d[keya].keys())

    for keyb in d:
        tempset &= d[keyb].keys()

        if len(tempset) >= 2:
            keys.add(keyb)

    print({key: d[key] for key in keys})

可能有用。在

编辑:不,不太管用。我得考虑一下。在

相关问题 更多 >