Search code examples
pythonalgorithmdictionarystructuredefaultdict

How to make a Python dictionary that keys have all related values


When key(1) has value(1) and key(2) has value(2) (Both value(1), (2) are set)

I want to add all of value(2) elements into the value(1) if key(2) is in value(1).

Here are some examples below.

d1 = {1: {2}, 2: {3}}
d2 = {1: {2, 3}, 2: {3}}

d3 = {1: {10, 20, 30}, 10: {11}, 20: {21}, 30: {31}}
d4 = {1: {10, 11, 20, 21, 30, 31}, 10: {11}, 20: {21}, 30: {31}}

d5 = {1: {2}, 2: {3}, 3: {4}}
d6 = {1: {2, 3, 4}, 2: {3, 4}, 3: {4}}

*I'd like to know how to make

d2 from d1 d4 from d3 d6 from d5*

In case d3 -> d4 d3 has key "1" and its values are "10", "20", "30" and d3 also has a key "10" and its value is "11" thus key "1" values turn into "10", "11", "20", "30" because key "1" has a value "10" and key "10" has a value "11". Repeat the same steps and finally key "1" gets values "10", "11", "20", "21", "30", "31"

Is there a better structure to resolve such a problem?

Just only keywords are also helpful to me.


Solution

  • This will work: It primarily uses set operations to perform comparisons.

    def solve(d):
        keys = set(d.keys())               # create a set of dictionary keys
        for k in keys:                     # for each key in dictionary
            values = set()                 # create an empty set
            while keys & d[k] ^ values:    # while values left  
                for val in d[k] ^ values:  # for each of the values
                    values.add(val)        # add it to the values set
                    d[k] |= d[val]         # expand the value for dictionary key
        return d                           # return dictionary
    
    d1 = {1: {2}, 2: {3}}
    d2 = {1: {2, 3}, 2: {3}}
    
    d3 = {1: {10, 20, 30}, 10: {11}, 20: {21}, 30: {31}}
    d4 = {1: {10, 11, 20, 21, 30, 31}, 10: {11}, 20: {21}, 30: {31}}
    
    d5 = {1: {2}, 2: {3}, 3: {4}}
    d6 = {1: {2, 3, 4}, 2: {3, 4}, 3: {4}}
    
    groups = [(d1,d2), (d3,d4), (d5,d6)]
    for before, after in groups:
        assert solve(before) == after  # assert that d1 equals d2 after function