Amistad Amistad - 3 months ago 11
Python Question

Converting a list of list into a dictionary based on common values in python

I have a list of list in python as follows:

a = [['John', 24, 'teacher'],['Mary',23,'clerk'],['Vinny', 21, 'teacher'], ['Laura',32, 'clerk']]


The idea is to create a dict on the basis of their occupation as follows:

b = {'teacher': {'John_24': 'true', 'Vinny_21' 'true'},
'clerk' : {'Mary_23': 'true', 'Laura_32' 'true'}}


What is the best way of achieving this ?

Answer

You can use a defaultdict:

a = [['John', 24, 'teacher'],['Mary',23,'clerk'],['Vinny', 21, 'teacher'], ['Laura',32, 'clerk']]


from collections import defaultdict

dct = defaultdict(defaultdict)


for name, age, occ in a:
    dct[occ][name] = "true"

Output:

from pprint import pprint as pp

pp(dict(dct))
 {'clerk': defaultdict(None, {'Laura_32': 'true', 'Mary_23': 'true'}),
'teacher': defaultdict(None, {'John_24': 'true', 'Vinny_21': 'true'})}

Although you may be as well just appendiing each name to a list:

from collections import defaultdict

dct = defaultdict(list)

for name, _, occ in a:
    dct[occ].append(name) 

Which woud give you:

 defaultdict(<class 'list'>, {'clerk': ['Mary_23', 'Laura_32'], 'teacher': ['John_24', 'Vinny_21']})

If you want to use the age later you may also wan to store them separately:

from collections import defaultdict

dct = defaultdict(list)


for name, age, occ in a:
    dct[occ].append([name, age])

Which would give you:

defaultdict(<class 'list'>,
            {'clerk': [['Mary', 23], ['Laura', 32]],
             'teacher': [['John', 24], ['Vinny', 21]]})

Using python3 you can use:

for *nm_age, occ in a:
    dct[occ].append(nm_age)
Comments