-1

I have the following data structure:

db['data'][products']

Inside that, i have a list of dicts:

[{'name':'John', 'id':1},
 {'name':'Matt', 'id':2}]

How to add a fix pair of key/value for each element of list ?

Results should be something like that:

[{'name':'John', 'id':1, 'new_key':'new_value'},
 {'name':'Matt', 'id':2, 'new_key':'new_value'}]

Thanks

Aven Desta
  • 2,114
  • 12
  • 27
BlackMath
  • 1,708
  • 1
  • 11
  • 14
  • 1
    [duplicate](https://stackoverflow.com/questions/14071038/add-an-element-in-each-dictionary-of-a-list-list-comprehension) – Aven Desta Jan 07 '21 at 11:20
  • 3
    Does this answer your question? [Add an element in each dictionary of a list (list comprehension)](https://stackoverflow.com/questions/14071038/add-an-element-in-each-dictionary-of-a-list-list-comprehension) – costaparas Jan 07 '21 at 11:21

2 Answers2

0

its just a list of dicts, iterate over them and update as needed:

for item in db['data']['products']:
    item['new_key'] = 'new_value'
Nullman
  • 4,179
  • 2
  • 14
  • 30
0

with list comprehension:

result = [dict(item, **{'new_key':'new_value'}) for item in db['data']['products']]