[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.