Skip to content Skip to sidebar Skip to footer

How To Cast A List To A Dictionary

I have a list as a input made from tuples where the origin is the 1st object and the neighbour is the 2nd object of the tuple. for example : inp : lst = [('a','b'),('b','a'),('c',

Solution 1:

The simplest is probably inside a try / except block:

lst = [('a','b'),('b','a'),('c',''),('a','c')]

out = dict()

for k, v in lst:
    try:
        if v != '':
            out[k][1].append(v)
        else:
            out[k][1].append([])

    except KeyError:
        if v != '':
            out[k] = (k, [v])
        else:
            out[k] = (k, [])

print out

Which gives:

{'a': ('a', ['b', 'c']), 'b': ('b', ['a']), 'c': ('c', [])}

Solution 2:

Here's how I did it, gets the result you want, you can blend the two operations into the same loop, make a function out of it etc, have fun! Written without Python one liners kung-fu for beginner friendliness!

>>> lst = [('a','b'),('b','a'),('c',''),('a','c')]
>>> out = {}
>>> for pair in lst:
... if pair[0] notin out:
...         out[pair[0]] = (pair[0], [])
...
>>> out
{'a': ('a', []), 'c': ('c', []), 'b': ('b', [])}
>>> for pair in lst:
...     out[pair[0]][1].append(pair[1])
...
>>> out
{'a': ('a', ['b', 'c']), 'c': ('c', ['']), 'b': ('b', ['a'])}

Solution 3:

Just here to mention setdefault

lst = [('a','b'),('b','a'),('c',''),('a','c')]

d = {}
for first, second in lst:
    tup = d.setdefault(first, (first, []))
    if second and second not in tup[1]:
        tup[1].append(second)

Post a Comment for "How To Cast A List To A Dictionary"