我在组合或计算这两个词典的共同/相等部分时遇到问题.在我的词典中,值列表:
d1 = {0:['11','18','25','38'], 1:['11','18','25','38'], 2:['11','18','25','38'], 3:['11','18','25','38']} d2 = {0:['05','08','11','13','16','25','34','38','40', '43'], 1:['05', '08', '09','13','15','20','32','36','38', '40','41'], 2:['02', '08', '11', '13', '18', '20', '22','33','36','39'], 3:['06', '11', '12', '25', '26', '27', '28', '30', '31', '37']}
我想检查"d2"并知道"d1"中是否有数字.如果有一些,我想用新数据更新其中一个或接收第三个字典"d3",只有"d1"和"d2"中相同/相等的值,如:
d3 = {0:['11','25','38'], 1:['38'], 2:['11','18'], 3:['11','25']}
谁能帮我这个?
我的错,我忘了更具体.我在寻找Python的解决方案.
假设这是Python,你想要:
dict((x, set(y) & set(d1.get(x, ()))) for (x, y) in d2.iteritems())
生成结果字典"d3".
>>> d3 = {k: list(set(d1.get(k,[])).intersection(v)) for k, v in d2.items()} {0: ['11', '25', '38'], 1: ['38'], 2: ['11', '18'], 3: ['11', '25']}
上述版本(以及Python 2.x版本)允许空交叉,因此在一般情况下需要额外的过滤:
>>> d3 = {k: v for k, v in d3.items() if v}
将上述内容合并为一遍:
d3 = {} for k, v in d2.items(): # find common elements for d1 & d2 v3 = set(d1.get(k,[])).intersection(v) if v3: # whether there are common elements d3[k] = list(v3)
[编辑:我发布了这个帖子社区维基,以便人们可以根据需要改进它.我承认如果你不习惯在Python中阅读这类东西,可能会有点难以阅读.