簡體   English   中英

如何將列表元素添加到 python 中的字典列表中

[英]How to add element of a list to list of dictionary in python

我正在嘗試將列表元素添加到列表字典中,我已盡我所能,但無法完成。

字典列表

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'}]

列表

rev_per_emp = [217391.30434782608,376142.84374767606,911953.2812190612]

所需 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}]

我將不勝感激完成這項工作的任何幫助。 謝謝

這就是你需要的:)

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

可以這樣做:

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

當然,您必須確保兩個列表的大小相同

使用這樣的枚舉器

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

這將使它:

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

print(fortunne_500)

你可以試試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM