【问题标题】:Convert values of a dictionary into key value pair将字典的值转换为键值对
【发布时间】:2021-07-06 09:58:14
【问题描述】:

我有一个示例字典

sample_dict = [{"id":1, "count":10},
               {"id":2, "count":20},
               {"id":3, "count":30}]

我想要这样的东西

sample_dict = [{1: 10}, {2: 20}, {3: 30}]

我怎样才能以最佳方式做到这一点?

【问题讨论】:

  • 您的非最佳解决方案是什么样的?
  • 目前我正在遍历列表并获取“id”和“count”的值并创建一个新的字典并将其附加到另一个列表中
  • @Logan 有什么不好的?
  • 请出示您的代码,以便我们编写更优化的解决方案
  • 你的样本是字典列表,不是字典,结果也是字典列表。

标签: python list dictionary


【解决方案1】:

你可能想要一个这样的对象:

sample_dict = [{"id":1, "count":10},{"id":2, "count":20},{"id":3, "count":30}]

out = { o['id']: o['count'] for o in sample_dict }
print(out) # {1: 10, 2: 20, 3: 30}
print(out[2]) # 20

请注意,虽然idcount 值是按顺序排列的,但这不是此方法的要求。只要 id 值是唯一的,这将起作用。

【讨论】:

    【解决方案2】:
    sample_dict = [{"id":1, "count":10},
                   {"id":2, "count":20},
                   {"id":3, "count":30}]
    
    output = []
    for elem in sample_dict:
        new_dict = {elem["id"]: elem["count"]}
        output.append(new_dict)
    

    打印输出将返回

    print(output)
    
    [{1: 10}, {2: 20}, {3: 30}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      • 2017-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      相关资源
      最近更新 更多