Search code examples
python-3.xdictionarydefaultdict

Appending list as inner value in nested dictionary python


I'm trying to create a nested dictionary with this format:

d3 = {'343564': {'32.cnt':['eeo', 'eec', 'vp3'],
               'avg.ps': ['cpt', 'vp3', 'ern']}}

This what I have so far:

d2 = {}
for r,d,f in os.walk(path):
    for n in f:
        if n.endswith(('txt', 'sub','avg', 'dat')):
            pass
        if n.endswith('32.cnt'):
            split=n.split("_")
            d2.setdefault(split[3], []).append({split[-1]:split[0]})

but it returns this:

{'343564': [{'32.cnt': 'eeo'},
  {'32.cnt': 'eec'},
  {'32.cnt': 'vp3'},
  {'avg.ps': 'cpt'},
  {'avg.ps': 'vp3'}
  {'avg.ps': 'ern}

How can I "collapse" the inner key into 1 key and create a list from the inner values?


Solution

  • I guessed at a filename format that works with what it looks like you are attempting:

    from collections import defaultdict
    from pprint import pprint
    d2 = defaultdict(lambda:defaultdict(list))
    for n in ['eeo_xxx_xxx_343564_32.cnt','eec_xxx_xxx_343564_32.cnt','vp3_xxx_xxx_343564_32.cnt',
              'cpt_xxx_xxx_343564_avg.ps','vp3_xxx_xxx_343564_avg.ps','ern_xxx_xxx_343564_avg.ps']:
        split=n.split("_")
        d2[split[3]][split[-1]].append(split[0])
    
    pprint(d2)
    

    Output:

    {'343564': {'32.cnt': ['eeo', 'eec', 'vp3'],
                'avg.ps': ['cpt', 'vp3', 'ern']}}