字典的维恩图是散列还是字典?

2024-04-25 09:34:37 发布

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

我有两本字典(每本80K个条目),格式都一样:

A= {'1':'a', '2':'b', '3':'c', '4':'d'}

B= {'2':'b', '3':'a', '4':'d', '5':'e'}

一些键:值对从Dict\u A和Dict\u B重叠。把这些字典看作维恩图圆。我的目标是找到这两个字典的重叠部分并生成新的字典:Dict\u A、Dict\u B、Dict\u C和Dict\u D。 最后,我想总结出6本字典: 在哪里

原始词典:

A= {'1':'a', '2':'b', '3':'c', '4':'d'}
B= {'2':'b', '3':'a', '4':'d', '5':'e'}

Dict_A:具有唯一键的项目

Dict_A = {'1':'a'}

Dict_B:具有B所独有的键的项

Dict_B = {'5':'e'}

Dict_C:具有由A和B共享的键,但值不同的项

Dict_C = {'3':'a', '3':'c'}

dictd:A和B共享键和值的项

Dict_D = {'2':'b', '4':'d'}

我知道如何通过设置来确定这些东西的长度:

shared1 = set(A.items()) & set(B.items())

shared2 = set(A.keys()) & set(B.keys())

然后我就可以知道字典里应该有多少: len(shared2)-len(shared1)

但我不知道怎么做字典。你知道吗


Tags: 项目目标len字典格式条目itemskeys
1条回答
网友
1楼 · 发布于 2024-04-25 09:34:37

由于字典查找时间很快(O(1),因此可以使用字典理解:

>>> # use iteritems on Python2
>>> shared1 = {k: v for k, v in A.items() if i in B}

Dict_A: items with keys unique to A

Dict_B: items with keys unique to B

>>> Dict_A = {k: v for k,v in A.items() if k not in B}
>>> Dict_B = {k: v for k,v in B.items() if k not in A}

用于以后的任务,例如:

Dict_C: items with keys shared by A and B, but with values that are different

您可以使用列表理解:

>>> # use iteritems for Python2
>>> # list comprehension
>>> shared1 = [k for k, v in A.items() if B.get(k) == v]
>>> # set comprehension
>>> shared1 = {k for k, v in A.items() if B.get(k) == v}

记住,键必须是唯一的,并且您只需要不同的键:一个列表(或一个集合)就足够了(使用花括号或集合理解来生成一个集合)。你知道吗

Dict_D: items with keys AND values shared by A and B.

就用上面的想法吧

>>> Dict_D = {k: v for k, v in A.items() if B.get(k) == v}

相关问题 更多 >