Home > Enterprise >  Python: how to converet list of list into a dictionary
Python: how to converet list of list into a dictionary

Time:11-08

I am trying to converet the list of list into a dictionary using defaultdict method.

I have a list of list:

a= [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]

I want the output in this format:

{1: [0], 2: [0], 2: [1], 3: [1], 4: [1], 4: [2], 5: [2], 6: [2], 3: [3], 7: [3], 6: [4], 10: [4]})

Here is my code:

a =[[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]

clusters = defaultdict(list)
cluster_sz = {}

cliques = []
cluster_idx = 0

for clique in a:
       cliques.append(clique)
       for v in clique:
           clusters[v].append(cluster_idx) 
       cluster_idx =1
print(clusters)

The output of this code is:

{1: [0], 2: [0,1], 3: [1,3], 4: [1, 2], 5: [2], 6: [2, 4], 7: [3], 10: [4]})

But I need this type of output:

{1: [0], 2: [0], 2: [1], 3: [1], 4: [1], 4: [2], 5: [2], 6: [2], 3: [3], 7: [3], 6: [4], 10: [4]})

CodePudding user response:

Here is a shortened code with your desired output.

a = [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]

d = {}

for i, sublist in enumerate(a):
    for num in sublist:
        if num not in d:
            d[num] = []
        d[num].append(i)

print(d)

CodePudding user response:

dict = {1: [0], 2: [0,1], 3: [1,3], 4: [1, 2], 5: [2], 6: [2, 4], 7: [3], 10: [4]}
convertedDict = {}

for (i, j) in dict.items():
    if len(j) > 1:
        for k in j:
            convertedDict[i] = [k]
    else:
        convertedDict[i] = j
        
        
print (convertedDict)

{1: [0], 2: [1], 3: [3], 4: [2], 5: [2], 6: [4], 7: [3], 10: [4]}


Those object, have duplicated keys, thats the reason, why, converted dict saving only last value in last iteration.

https://thispointer.com/can-a-dictionary-have-duplicate-keys-in-python/

CodePudding user response:

You can try with this approach So instead of dictionary with overlapping keys, you can create list of dictionaries.

a= [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]
b = [{r:i} for i,k in enumerate(a) for r in k ]

[{1: 0}, {2: 0}, {2: 1}, {3: 1}, {4: 1}, {4: 2}, {5: 2}, {6: 2}, {3: 3}, {7: 3}, {6: 4}, {10: 4}]
  • Related