简体   繁体   中英

How to add element of a list to list of dictionary in python

Am trying to add element of a list to a list dictionary, I have tried all my possible best but could not get it done.

list of dict

fortunne_500=[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion'},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion'},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion'}]

list

rev_per_emp = [217391.30434782608,376142.84374767606,911953.2812190612]

Desired output

[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion',
  'rev per emp': 217391.30434782608},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion',
  'rev per emp': 376142.84374767606},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion',
  'rev per emp': 911953.2812190612}]

I will appreciate any help in getting this done. Thank you

This is what you need:)

for fortunne_dict,rpe in zip(fortunne_500,rev_per_emp):
  fortunne_dict['rev per emp'] = rpe

It can be done like this:

for i in range(len(fortunne_500)):
  fortunne_500[i]["ref per emp"]=ref_per_emp[i]

Of course, you have to make sure, that both lists have the same size

using a enumerator like this

    for i, item in enumerate(fortunne_500):
        item["rev per emp"] = rev_per_emp[i]

This would make it:

for ix, val in enumerate(rev_per_emp):
    fortunne_500[ix].update({"rev per emp": val})

print(fortunne_500)

You could try this:

myit = iter(rev_per_emp)
for dict in fortunne_500:
  dict['rev_per_emp'] = next(myit)

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