What is a faster way to combine the values ​​of this Python structure into a single dictionary?

I updated the way to create a federated dictionary ( all_classes) below, but I wonder if it can be more efficient.

I have a dictionary of dictionaries, for example:

groups_and_classes = {'group_1': {'class_A': [1, 2, 3],
                                  'class_B': [1, 3, 5, 7], 
                                  'class_c': [1, 2], # ...many more items like this
                                 },
                      'group_2': {'class_A': [11, 12, 13],
                                  'class_C': [5, 6, 7, 8, 9]
                                 }, # ...and many more items like this
                     }

The function creates a new object from groups_and_classes, like this (the function to create this is called often):

all_classes = {'class_A': [1, 2, 3, 11, 12, 13],
               'class_B': [1, 3, 5, 7, 9],
               'class_C': [1, 2, 5, 6, 7, 8, 9]
              }

Right now there is a loop that does this:

all_classes = {}
for group in groups_and_classes.values():
    for c, vals in group.iteritems():
        for v in vals:
            if all_classes.has_key(c):
                if v not in all_classes[c]:
                    all_classes[c].append(v)
            else:
                all_classes[c] = [v]

So far I have changed the code to use setinstead list, since the order of the list does not matter, and the values ​​must be unique:

all_classes = {}
for group in groups_and_classes.values():
    for c, vals in group.iteritems():
        try:
            all_classes[c].update(set(vals))
        except KeyError:
            all_classes[c] = set(vals)

This is a little better, and I did not need to convert sets to lists because of the way it is all_classesused in the code.

: all_classes ( groups_and_classes , )?

+3
3

, :

from collections import defaultdict
all_classes = defaultdict(set)
for group in groups_and_classes.values():
    for c, vals in group.iteritems():
        all_classes[c].update(set(vals))

Defaultdicts - , , .:)

+4

, , , :

all_classes[c].update(vals)

update , , .

+2

A combination of list dictionaries in Python .

def merge_dols(dol1, dol2):
    result = dict(dol1, **dol2)
    result.update((k, dol1[k] + dol2[k]) for k in set(dol1).intersection(dol2))
    return result

g1 = groups_and_classes['group_1']
g2 = groups_and_classes['group_2']

all_classes = merge_dols(g1,g2)

OR

all_classes = reduce(merge_dols,groups_and_classes.values())

- copied from Alex Martelli

If you get more than two groups, you can use itertools.reduce

all_classes = reduce(merge_dols,groups_and_classes.values())
+2
source

Source: https://habr.com/ru/post/1736657/


All Articles