dictionary - Python-how to merge and not update two dictionaries with strings as keys and values as list of strings? -
given 2 dictionaries:
d1={'cardinal':['va','oh'], 'meadowlark':['or']} d2={'meadowlark':['wy'], 'cardinal':['va', 'il'], 'oriole':['md']}
how merge them new dictionary without updating original dictionaries and concatenate duplicates so:
new_dict={'cardinal':['va','oh','va','il'],'meadowlark':['or', 'wy'], 'oriole':['md']}
my code doesn't concatenate correctly here is:
def merge(d1,d2): import collections a=collections.counter(d1) b=collections.counter(d2) return a+b
i'm stuck on how concatenate items.
deep-copy 1 of dicts, extend values elements of values other dict needed.
>>> copy import deepcopy >>> d1={'cardinal':['va','oh'], 'meadowlark':['or']} >>> d2={'meadowlark':['wy'], 'cardinal':['va', 'il'], 'oriole':['md']} >>> >>> d = deepcopy(d1) >>> key, lst in d2.items(): ... d.setdefault(key, []).extend(lst) ... >>> d {'meadowlark': ['or', 'wy'], 'oriole': ['md'], 'cardinal': ['va', 'oh', 'va', 'il']} >>> d1 {'meadowlark': ['or'], 'cardinal': ['va', 'oh']} >>> d2 {'meadowlark': ['wy'], 'oriole': ['md'], 'cardinal': ['va', 'il']}
Comments
Post a Comment