Ale
Ale

Reputation: 665

How to merge data from multiple dictionaries with repeating keys?

I have two dictionaries:

dict1 = {'a': '2', 'b': '10'}
dict2 = {'a': '25', 'b': '7'}

I need to save all the values for same key in a new dictionary.

The best i can do so far is: defaultdict(<class 'list'>, {'a': ['2', '25'], 'b': ['10', '7']})

dd = defaultdict(list)
for d in (dict1, dict2):
    for key, value in d.items():
        dd[key].append(value)
print(dd)

that does not fully resolve the problem since a desirable result is:

a = {'dict1':'2', 'dict2':'25'}
b = {'dict2':'10', 'dict2':'7'}

Also i possibly would like to use new dictionary key same as initial dictionary name

Upvotes: 1

Views: 68

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

As @Prune suggested, structuring your result as a nested dictionary will be easier:

{'a': {'dict1': '2', 'dict2': '25'}, 'b': {'dict1': '10', 'dict2': '7'}}

Which could be achieved with a dict comprehension:

{k: {"dict%d" % i: v2 for i, v2 in enumerate(v1, start=1)} for k, v1 in dd.items()}

If you prefer doing it without a comprehension, you could do this instead:

result = {}
for k, v1 in dd.items():
    inner_dict = {}

    for i, v2 in enumerate(v1, start=1):
        inner_dict["dict%d" % i] = v2

    result[k] = inner_dict

Note: This assumes you want to always want to keep the "dict1", "dict2",... key structure.

Upvotes: 0

Prune
Prune

Reputation: 77837

Your main problem is that you're trying to cross the implementation boundary between a string value and a variable name. This is almost always bad design. Instead, start with all of your labels as string data:

table = {
    "dict1": {'a': '2',  'b': '10'},
    "dict2": {'a': '25', 'b': '7'}
}

... or, in terms of your original post:

table = {
    "dict1": dict1,
    "dict2": dict2
}

From here, you should be able to invert the levels to obtain

invert = {
    "a": {'dict1': '2',  'dict2': '25'},
    "b": {'dict2': '10', 'dict2': '7'}
}

Is that enough to get your processing where it needs to be? Keeping the data in comprehensive dicts like this, will make it easier to iterate through the sub-dicts as needed.

Upvotes: 1

Related Questions