【问题标题】:How to add element of a list to list of dictionary in python如何将列表的元素添加到python中的字典列表中
【发布时间】:2020-09-18 04:45:45
【问题描述】:

我正在尝试将列表元素添加到列表字典中,我已尽我所能,但无法完成。

字典列表

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]

期望的输出

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

如果能帮我完成这件事,我将不胜感激。 谢谢

【问题讨论】:

标签: python list dictionary append


【解决方案1】:

你可以试试这个:

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

【讨论】:

    【解决方案2】:

    这样就可以了:

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

    【讨论】:

      【解决方案3】:

      使用这样的枚举器

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

      【讨论】:

        【解决方案4】:

        可以这样做:

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

        当然,您必须确保两个列表的大小相同

        【讨论】:

          【解决方案5】:

          这就是你需要的:)

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-10-29
            • 1970-01-01
            • 2013-01-31
            • 2011-03-22
            • 1970-01-01
            相关资源
            最近更新 更多