【问题标题】:function to add dicts to a nested dict that give increasing keys将字典添加到嵌套字典的函数,以增加键
【发布时间】:2021-08-26 22:27:31
【问题描述】:

假设我有一本空字典。我将如何编写一个将其他字典添加到空字典的函数,并为其提供一个键,该键会随着添加的每个新字典而增加?

所以它会导致类似:

{0: {'name': 'pork', 'cals': 100, 'pro': 10, 'sugar': 1},
 1: {'name': 'chicken', 'cals': 190, 'pro': 19, 'sugar': 19},
 2: {'name': 'beef', 'cals': 160, 'pro': 12, 'sugar': 2}}

【问题讨论】:

  • 自己试一试并发布您的尝试。

标签: python dictionary nested


【解决方案1】:
dict_of_dicts = dict(enumerate(list_of_dicts))

【讨论】:

    【解决方案2】:

    您可以创建一个要添加的词典列表,然后使用简单的 for 循环将它们添加到您的词典中:

    result = {}
    ex1 = {'name': 'pork', 'cals': 100, 'pro': 10, 'sugar': 1}
    ex2 = {'name': 'chicken', 'cals': 190, 'pro': 19, 'sugar': 19}
    ex3 = {'name': 'beef', 'cals': 160, 'pro': 12, 'sugar': 2}
    listDict = [ex1,ex2,ex3]
    
    for i in range(len(listDict)):
      result[i] = listDict[i]
    print(result)
    

    输出:

    {0: {'name': 'pork', 'cals': 100, 'pro': 10, 'sugar': 1}, 1: {'name': 'chicken', 'cals': 190, 'pro': 19, 'sugar': 19}, 2: {'name': 'beef', 'cals': 160, 'pro': 12, 'sugar': 2}}
    

    【讨论】:

      【解决方案3】:

      下面是可以帮助你的代码:

      def add_dict(d1, out_dict):
          new_key = len(out_dict.keys())
          out_dict[new_key] = d1
          
      ex1 = {'name': 'pork', 'cals': 100, 'pro': 10, 'sugar': 1}
      ex2 = {'name': 'chicken', 'cals': 190, 'pro': 19, 'sugar': 19}
      ex3 = {'name': 'beef', 'cals': 160, 'pro': 12, 'sugar': 2}
      listDict = [ex1,ex2,ex3]
      
      out = {}
      for dict1 in listDict:
          add_dict(dict1, out)
          
      print (out)
      

      【讨论】:

        猜你喜欢
        • 2018-06-27
        • 2019-02-14
        • 2020-05-29
        • 2020-08-07
        • 1970-01-01
        • 2018-04-25
        • 2018-11-07
        • 1970-01-01
        • 2015-06-14
        相关资源
        最近更新 更多