Reputation: 1
I am working on a API request that return a list of nested dictionaries. The result is similar to this,
example=[{'transactionId':'1112234','customerID':1212,'total':360,'items':[{'productId':1a2345d23,'quantity':3,'price':160},{'productId':1a5645d99,'quantity':5,'price':200}],{
'transactionId':'11134674','customerID':1223,'total':120,'items':[{'productId':1a2345d27,'quantity':1,'price':60},{'productId':1a1145d22,'quantity':1,'price':60}}]]
I made a code to loop and append the newId to the list and was only able to insert the id to the parent dictionary.
result = [dict(item, newId= uuid.uuid4()) for item in example]
Any help would be greatly appreciated to attain my desire result like the one bellow.
example=[{'newId':1111,'transactionId':'1112234','customerID':1212,'total':360,'items':[{'newId':1111,'productId':1a2345d23,'quantity':3,'price':160},{'newId':1111,'productId':1a5645d99,'quantity':5,'price':200}],
{'newId':2222,'transactionId':'11134674','customerID':1223,'total':120,'items':[{'newId':2222,'productId':1a2345d27,'quantity':1,'price':60},{'newId':2222,'productId':1a1145d22,'quantity':1,'price':60}}]]
Upvotes: 0
Views: 788
Reputation: 9539
Your example data has syntax errors in it, so I wasn't able to test the following code, but I believe this is what you are looking for. You just need to do things the old fashioned way instead of doing list comprehension, and it becomes easy enough to do what you want.
result = []
for order in example:
order['newId'] = uuid.uuid4()
if 'items' in order:
for item in order['items']:
item['newId'] = uuid.uuid4()
Upvotes: 1