Home > Software engineering >  How to convert from a list of list to dictionary with uneven list elements?
How to convert from a list of list to dictionary with uneven list elements?

Time:04-28

I have the following list:

list_list = [("111", "222", "455"), ("134", "222", "666"), ("465", "364"), ("324", "364")]

I want the first element to be the value and the rest to be the keys in a dictionary. I also want to have multiple values for a key. This is the result that I want:

{'222': ['111' '134'], '455': ['111'], '666': ['134'], '364': ['465', '324']} 

I tried it in the following way but it doesn't work. Please help me with it

c = {}
            
for item in list_list:
                
    value = item[0]
                
    for each in range(1, len(item)):
                    
        c[item[each]] = value
            
print(c)

CodePudding user response:

You can achieve it this way :

list_list = [("111", "222", "455"), ("134", "222", "666"), ("465", "364"), ("324", "364")]

c = {}

for item in list_list:

    value = item[0]

    for each in range(1, len(item)):
        if item[each] in c.keys():
            c[item[each]].append(value)
        else:
            c[item[each]] = [value]

print(c)

For each new value, we check if the key already exists. As in your solution, you overwrite the keys that already have a value, here we either create the list, or append to the existing one if possible.

Output :

{'222': ['111', '134'], '455': ['111'], '666': ['134'], '364': ['465', '324']}
  • Related