比使用集合更快的比较字典的方法
我有两个大字典,它们具有唯一的键,但可能存在重叠的值。我想将每组字典值相互比较并找到重叠的数量。我已经使用两个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要“反转”一本(或两本)字典。
You want to "invert" one (or both) of your dictionaries.