如何在python中输出具有相同值的键到多个字典?

时间:2015-09-29 01:52:33

标签: python dictionary

鉴于我有3个字典,dicta,dictb,dictc,我将如何形成一个字典,key: value对是这样的,它们只能是所有字典中存在的键,并且值是等价的?

示例:

dicta = {"one": "foo", "two": "bar", "three": "biz"}
dictb = {"one": None, "two": "bar", "three": "foo", "four": "foo"}
dictc = {"one": None, "two": "bar", "three": False, "five": "foo"}

结果如下,因为在所有dicts中只有一个键值对保持相同:

{"two": "bar"}

此外,"三个词组"例子并不准确。我可能有三个词,我可能有两个,我可能有10个,等等。

3 个答案:

答案 0 :(得分:3)

由于字典键是唯一且可清除的,并且看起来您有字符串值(可以清除),您只需找到所有NSNumber的交集,然后将生成的items转换为set

dict

根据您的示例数据,result = dict(dicta.items() & dictb.items() & dictc.items()) 将根据需要为result

如果您使用的是Python 2,请使用{'two': 'bar'}代替viewitems()

答案 1 :(得分:2)

我认为你想要的是设置来自所有dicts的项目的交集。

WITH(nolock)

答案 2 :(得分:2)

这适用于任意数量的词组:

>>> dicta = {"one": "foo", "two": "bar", "three": "biz"}
>>> dictb = {"one": None, "two": "bar", "three": "foo", "four": "foo"}
>>> dictc = {"one": None, "two": "bar", "three": False, "five": "foo"}
>>> dictlist = [dicta, dictb, dictc]
>>> items = set(dictlist[0].items())
>>> for thedict in dictlist[1:]:
...     items &= set(thedict.items())
... 
>>> result = dict(items)
>>> result
{'two': 'bar'}

编辑正如DSM在下面指出的那样,您可以使用set.intersection采用多个参数将循环推送到Python的事实:

>>> dicta = {"one": "foo", "two": "bar", "three": "biz"}
>>> dictb = {"one": None, "two": "bar", "three": "foo", "four": "foo"}
>>> dictc = {"one": None, "two": "bar", "three": False, "five": "foo"}
>>> dict(set.intersection(*(set(x.items()) for x in (dicta, dictb, dictc))))
{'two': 'bar'}