t Book t Book - 1 month ago 4
Python Question

python create nested directory based on two lists

Good morning,

This might be easy but I´m just starting with python. For learning:
Is there are 'cleaner' way creating a nested dict based on two lists than this:

person = ['mama.a','mama.b', 'mama.c',
'mama.d', 'papa.a', 'papa.b']
kind = ['a', 'b', 'c', 'd']
combined = {}

# {'mama': {'a': [], 'c': [], 'b': [], 'd': []}, 'papa': {'a': [], 'c': [], 'b': [], 'd': []}}

for human in [i.split('.')[0] for i in person]:
combined[human] = {}
for attrib in kind:
combined[human][attrib] = []


What about making a set of the names. To ensure you only try to add each one to dict once.

combined = {}
for n in set(p.split('.')[0] for p in person):
    combined[n] = {k:[] for k in kind}

This could probably be made into a monster one-liner nested dict comprehension. Although I dont think it would be as easy to read.

or you could split the set out onto another line. It then becomes

pset = set(p.split('.')[0] for p in person)
pdict = {p: {k: [] for k in kind} for p in pset}

Where the second line is the same as @Faiz Haldes answer.