比较/组合两个字典 [英] Comparing/combining two dictionaries

查看:263
本文介绍了比较/组合两个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个键盘对的字典如下:

I have two dictionaries with key-value pairs as follows:

dict-1  ch:23, 100
        ch:24, 95

dict-2  Ch:23, 98
        ch:25, 100

并不是所有的键都存在于两个字典中,每个字典都包含大约20万个键值对。我想做的是比较或组合这两个,并产生一个输出文本文件,以便如果键在两个字典中,我得到这两个值,输出文件格式如下:

Not all keys are present in the both dictionaries and each dictionary contains approximately 200,000 key-value pairs. What I want to do is compare or combine these two and produce an output text file such that if the key is in both dictionaries, I get both values, with an output file format like:

ch:23   100   98         
ch:24   95    .    
Ch:25   .     100

我该怎么做?

推荐答案

注意如果您使用的是字典(除非OrderedDict),则不会保留订单,因此您的结果的最终顺序与您不一样在你的例子中描述

Note If you are using a dictionary (Unless OrderedDict), the order would not be preserved, so the final order of your result would not be same as you depicted in your example

回到你的例子
如果

Coming back to your example If

>>> d1={'ch:23': 100, 'ch:24': 95}
>>> d2={'ch:23': 98 ,'ch:25': 100}

尝试这个

>>> d3=collections.defaultdict(list)
>>> for k,e in d1.items()+d2.items():
    d3[k].append(e)

如果要保留订单,您需要首先创建原始字典作为有序字典

If you want to preserve the Order, you need to create the original dictionary as an ordered dict in the first instance

然后您可以做为

>>> d1
OrderedDict([('ch:23', 100), ('ch:24', 95)])
>>> d2
OrderedDict([('ch:23', 98), ('ch:25', 100)])
>>> d3=collections.OrderedDict()
>>> for k,e in d1.items()+d2.items():
    d3.setdefault(k,[]).append(e)   
>>> d3
OrderedDict([('ch:23', [100, 98]), ('ch:24', [95]), ('ch:25', [100])])
>>> 

这篇关于比较/组合两个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆