由键合并的两个词典的价值联盟

时间:2015-06-27 21:19:29

标签: python python-2.7 dictionary


我有两个词典:

d1 = {'a':('x','y'),'b':('k','l')}
d2 = {'a':('m','n'),'c':('p','r')}

如何合并这两个词典以获得此类结果:

d3 = {'a':('x','y','m','n'),'b':('k','l'),'c':('p','r')}

当字典的值是简单类型(如int或str:

)时,这种方法有效
d3 = dict([(i,a[i]+b[i]) for i in set(a.keys()+b.keys())])

但我不知道如何处理列表作为值......

注意:我的问题与How to merge two Python dictionaries in a single expression?不同,因为我不想更新值但是添加它们

4 个答案:

答案 0 :(得分:3)

关于变量名称你的问题有点严重,但我认为这可以做你想要的:

tuples

请注意,您可以使用+添加(即扩展)ffmpeg -i 1.m4a -af silenceremove=1:0.5:0:1:0.5:0 2.m4a ffmpeg -i 1.m4a -af silenceremove=1:0.5:0:1:0.5:0 -ab 253k 3.m4a

答案 1 :(得分:1)

在Python中添加列表没有问题(它将它们连接起来);但是,在确定何时添加时会出现一些问题,因为只有当键出现在两个词典中时才应该这样做。

d3 = dict(
    [(i, d1[i]+d2[i]) for i in set(d1.keys()).intersection(d2.keys())] +\
    [(i, d1[i]) for i in set(d1.keys()) - set(d2.keys())] +\
    [(i, d2[i]) for i in set(d2.keys()) - set(d1.keys())])
>> d3
{'a': ('x', 'y', 'm', 'n'), 'b': ('k', 'l'), 'c': ('p', 'r')}

答案 2 :(得分:1)

两件事:

  1. 可以只添加应该有用的列表和元组。

    In [5]: ('x','y') + ('m','n')

    Out[5]: ('x', 'y', 'm', 'n')

  2. d3 = dict([(i,a[i]+b[i]) for i in set(a.keys()+b.keys())])在任何情况下都会失败,其中某个密钥只显示在ab中,但不会同时显示在d3 = {} for i in set(a.keys()+b.keys()): val1 = a[i] if i in a else () val2 = b[i] if i in b else () d3[i] = val1+val2 CREATE OR REPLACE TRIGGER MySchema.checkBalance AFTER INSERT ON MySchema.Orders FOR EACH ROW DECLARE v_count pls_integer; BEGIN SELECT goodcount INTO v_count FROM goods WHERE id = :new.gid; If v_count < :new.gcount Then raise_application_error (-20001,'Low inventory.'); End If; END; 中。这里的价值观无关紧要。

  3. 就个人而言,我会选择以下内容:

    +(void)showPickerViewInView: (UIView *)view
                    withStrings: (NSArray *)strings
                    withOptions: (NSDictionary *)options
                     completion: (void(^)(NSString *selectedString))completion;
    
    +(void)showPickerViewInView: (UIView *)view
                    withObjects: (NSArray *)objects
                    withOptions: (NSDictionary *)options
        objectToStringConverter: (NSString *(^)(id object))converter
           completion: (void(^)(id selectedObject))completion;
    
    +(void)dismissWithCompletion: (void(^)(NSString *))completion;
    

答案 3 :(得分:1)

您可以将dict.viewitems与for循环一起使用:

d1 = {'a': ('x', 'y'), 'b': ('k', 'l')}
d2 = {'a': ('m', 'n'), 'c': ('p', 'r')}

d3 = {}

for key, item in d1.viewitems() | d2.viewitems():
    d3[key]= d3.get(key,()) + item

print(d3)

{'a': ('x', 'y', 'm', 'n'), 'c': ('p', 'r'), 'b': ('k', 'l')}

或使用defaultdict:

from collections import defaultdict
d3 = defaultdict(tuple)
for key, item in d1.viewitems() | d2.viewitems():
    d3[key] += item

print(d3)

或者对列表使用viewkeys,因为它们不可清除:

d1 = {'a': ['x', 'y'], 'b': ['k', 'l']}
d2 = {'a': ['m', 'n'], 'c': ['p', 'r']}


d3 = {}

for key in d1.viewkeys() | d2.viewkeys():
    d3[key] = d1.get(key, []) + d2.get(key, [])

print(d3)

你可以写成dict comp:

d3 = {key:d1.get(key, []) + d2.get(key, []) for key in  d1.viewkeys() | d2.viewkeys()}

对于您也可以链接项目的列表:

d1 = {'a': ['x', 'y'], 'b': ['k', 'l']}
d2 = {'a': ['m', 'n'], 'c': ['p', 'r']}


from collections import defaultdict
d3 = defaultdict(list)
from itertools import chain
for key, v in chain.from_iterable((d1.items(),d2.items())):
    d3[key] += v

print(d3)

defaultdict(<type 'list'>, {'a': ['x', 'y', 'm', 'n'], 'c': ['p', 'r'], 'b': ['k', 'l']})

对于python3,只需使用.items.keys,因为它们会返回dictview对象。