比使用集合更快的比较字典的方法

发布于 2024-12-23 07:49:08 字数 532 浏览 0 评论 0原文

我有两个大字典,它们具有唯一的键,但可能存在重叠的值。我想将每组字典值相互比较并找到重叠的数量。我已经使用两个 for 循环和 set 完成了此操作,但我想知道是否有更快/更优雅的方法来执行此操作。

dic1 = {'a': ['1','2','3'], 'b':['4','5','6'], 'c':['7','8','9']}
dic2 = {'d': ['1','8','9'], 'e':['10','11','12'], 'f':['7','8','9']}

final_list=[]
for key1  in dic1:
    temp=[]    
    for key2 in dic2:
        test  = set(dic1[key1])
        query = set(dic2[key2])
        x = len(test & query)
        temp.append( [key2, x] )
    final_list.append([key1, temp])

I have two large dictionaries with unique keys but possibly overlapping values. I want to compare each set of dictionary values against each other and find the number of overlaps. I have done this using two for loops and set but am wondering if there is a faster/more elegant way to do this.

dic1 = {'a': ['1','2','3'], 'b':['4','5','6'], 'c':['7','8','9']}
dic2 = {'d': ['1','8','9'], 'e':['10','11','12'], 'f':['7','8','9']}

final_list=[]
for key1  in dic1:
    temp=[]    
    for key2 in dic2:
        test  = set(dic1[key1])
        query = set(dic2[key2])
        x = len(test & query)
        temp.append( [key2, x] )
    final_list.append([key1, temp])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傻比既视感 2024-12-30 07:49:08

您想要“反转”一本(或两本)字典。

val1 = defaultdict(list)
for k in dic1:
    for v in dic1[k]:
        val[v].append( k )
# val1 is a dictionary with each value mapped to the list of keys that contain that value.

for k in dic2: 
    for v in dic2[k]:
        val1[v] is the list of all keys in dic1 that have this value

You want to "invert" one (or both) of your dictionaries.

val1 = defaultdict(list)
for k in dic1:
    for v in dic1[k]:
        val[v].append( k )
# val1 is a dictionary with each value mapped to the list of keys that contain that value.

for k in dic2: 
    for v in dic2[k]:
        val1[v] is the list of all keys in dic1 that have this value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文