简体   繁体   中英

How to add a list of values to a list of nested dictionaries?

I would like to add each value of a list to each nested dictionary of a different list, with a new key name.

List of dictionaries:

list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]

List:

list = ['en', 'nl']

Desired output:

list_dicts = [{'id': 1, 'text': 'abc', 'language': 'en'}, {{'id':2, 'text': 'def', 'language':'nl'}]

Current method used: I transformed the list_dicts to a Pandas data frame, added a new column 'language' that represents the list values. Then, I transformed the Pandas data frame back to a list of dictionaries using df.to_dict('records') . There must be a more efficient way to loop through the list and add each value to a new assigned key in the list of dictionaries without needing to use Pandas at all. Any ideas ?

Using a list comprehension with zip

Ex:

list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]
lst = ['en', 'nl']

list_dicts = [{**n, "language": m} for n,m in zip(list_dicts, lst)]
print(list_dicts)
# --> [{'id': 1, 'text': 'abc', 'language': 'en'}, {'id': 2, 'text': 'def', 'language': 'nl'}]

A simple loop over the zipped lists will do:

for d, lang in zip(list_dicts, list):
    d["language"] = lang

Side note: you shouldn't name a variable list not to shadow built-in names.

Try like this (Dont use list as variable name):

list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]
langlist = ['en', 'nl']
x = 0
for y in list_dicts:
  y['language'] = langlist[x]
  x=x+1

print(list_dicts)
list = ['en', 'nl']   # Don't use list as variable name tho.
list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]


for i,item in enumerate(list):
    list_dicts[i]['language'] = item

that should do the trick, if you only want to assign values to the 'language' key.

Simply:

for d, l in zip(list_dicts, list):
    d['language'] = l

Then:

print(list_dicts)

(Assuming that both lists are of the same length)

list_dicts = [{'id': 1, 'text': 'abc'}, {'id':2, 'text': 'def'}]

list_lang = ['en', 'nl'] 

for i in range(len(list_dicts)):
    list_dicts[i]['language']=list_lang[i]

>>> print(list_dicts)
[{'id': 1, 'text': 'abc', 'language': 'en'}, {'id': 2, 'text': 'def', 'language': 'nl'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM