[Solved] How create dict from lists of list? [closed]


Assuming that you want to name your keys as key1, key2.. and so on when a key is not found:

l = [['a',1], ['b',2], [3], ['d',4]]

d = {}
i = 1
for x in l:
    try:
        d[x[0]] = x[1]
    except IndexError:
        d['key'+str(i)] = x[0]
        i += 1

print(d)

Output:

{'a': 1, 'b': 2, 'key1': 3, 'd': 4}

Note, this solution assumes that list will always contain list having 1 or 2 elements only.

1

solved How create dict from lists of list? [closed]