Reputation: 11
I am struggling with how to define a list and append to it while looping through parsed json doc. I can't append to the list that's not defined. But I don't want to set to empty list, as that would override values I had in it in next iteration. This is what I have:
from collections import defaultdict
nested_dict = lambda: defaultdict(nested_dict)
hash = nested_dict()
for e in decoded_jason['volumeList']:
volumeName = e['name']
volumeType = e['volumeType']
if volumeType == 'Snapshot':
consistencyGroupId = e['consistencyGroupId']
#I am missing a step here to initialize empty list so I can append
hash['map']['consistencyGroup'][consistencyGroupId].append(volumeName)
if I do this before append, it works, but then the list will be set to empty in next iteration:
hash['map']['consistencyGroup'][consistencyGroupId]=[]
hash['map']['consistencyGroup'][consistencyGroupId].append(volumeName)
Upvotes: 1
Views: 61
Reputation: 46923
Make your final line be:
hash['map']['consistencyGroup'].setdefault(consistencyGroupId, []).append(volumeName)
setdefault
either returns the value for the key if it's present, or, if it's not, sets it to the provided default ([]
in this case), and then returns that.
Upvotes: 2