Search code examples
pythonalgorithmdictionarykey-value-coding

Producing key:value pairs from existing pairs in nested dictionary


I have a rather algorithmic question. I’m using Python so that would be a bonus but in essence it’s about how to approach a problem.

I have a nested dictionary where for each customer, there are their relations with another customers. Basically if they enjoy same things, they are more compatible. The way this is calculated is that, for first customer the compatibility is calculated with every other customers, but for the second customer’s loop first one is skipped because it had been calculated already. You end up a dictionary something like this

Custdict={‘1’:{‘2’:1,’3’:0,’4’:3},’2’:{‘3’:1,’4’:2}…}

So for the last customer let’s say 10th, there is no entry for it as a key/value pair since it’s calculated in previous ones. My question is, how can I obtain this data from previous ones and add them as key/values in later ones. So above dictionary should become

Custdict={‘1’:{‘2’:1,’3’:0,’4’:3},’2’:{‘1’:1,‘3’:1,’4’:2}…}

I did something online search to see if there is such algorithm but couldn’t find anything


Solution

  • As a simple solution, you can just iterate over all values in the dictionary, and for each customer-customer pair (i, j), you also set the value for (j, i).

    from collections import defaultdict
    cust = {
        1: {
            2: 1,
            3: 0
        },
        2: {
            3: 1
        }
    }
    new_cust = defaultdict(dict)
    for customer in cust.keys():
        for neighbour in cust[customer].keys():
            new_cust[neighbour][customer] = cust[customer][neighbour]
            new_cust[customer][neighbour] = cust[customer][neighbour]
    print(dict(new_cust))
    # prints {2: {1: 1, 3: 1}, 1: {2: 1, 3: 0}, 3: {1: 0, 2: 1}}