0

[PYTHON 3.7 - Append to list for dictionary key]

How do I append to a list for a dictionary key when the keys are being created within the for loop?


Background:

I am parsing a .xml file to a nested OrderedDict and I recursively flatten out the OrderedDict into a list that has three elements: [level_depth, key, value].

This is my recursive function:

def iterdict(d, lvl, ARR):
    for k, v in d.items():
        if isinstance(v, dict):
            lvl += 1
            iterdict(v, lvl, ARR)
        elif isinstance(v, list):
            for i in v:
                if isinstance(i, dict):
                    lvl += 1
                    iterdict(i, lvl, ARR)
        else:
            print(lvl, k, v)
            ARR.append([lvl, k, v])
    return ARR

This is my attempt to create a dict where all the level_depth values are grouped as a single key:

A = iterdict(my_dict, 0, [])

A_dict = {}
for i in A:
    A_dict[str(i[0])].append(i[:-1])

Error:

A_dict[str(i[0])].append([i[:-1]]) KeyError: '1'

This is a sample output of the A list:

[...,  [17, '@Name', 'ExternalVisible'], [17, '@SystemDefined', 'true'], [17, '#text', 'false'], 
[18, '@Name', 'ExternalWritable'], [18, '@SystemDefined', 'true'], [18, '#text', 'false'], 
[19, '@Informative', 'true'], [19, '@Name', 'UserVisible'], ...]

Query Details

So I understand that the key error comes up because there is no list at that key to append to. How can I create a key with a new list and then append to it?

Example of my required result using the sample output:

A_dict = {..., '17': [['@Name', 'ExternalVisible'], ['@SystemDefined', 'true'], ['#text', 'false']]...}

Any advice on best practice will be appreciated too, thanks in advance.

leopardxpreload
  • 767
  • 5
  • 17
  • Does this answer your question? [Python dict how to create key or append an element to key?](https://stackoverflow.com/questions/12905999/python-dict-how-to-create-key-or-append-an-element-to-key) – AMC Mar 11 '20 at 00:29

1 Answers1

2

How can I create a key with a new list and then append to it?

you can use dict.setdefault:

A_dict = {}
for i in A:
    A_dict.setdefault(str(i[0]), []).append(i[:-1])

or you can use collections.defaultdict:

 import collections
 A_dict = collections.defaultdict(list)
kederrac
  • 16,819
  • 6
  • 32
  • 55