【问题标题】:Insert into dictionary with the same key name [python]插入具有相同键名的字典[python]
【发布时间】:2021-04-14 11:47:27
【问题描述】:

试图从字典列表中创建一个新字典;那些字典有重复的键名我需要将这些键与值附加到一个新的空字典

items=[
         {
            'actual_batch_qty': 5,
            'actual_qty': 6,
            'allow_zero_valuation_rate': 4,
            'amount': 80.0,
            'base_amount': 80.0,
         },
         {
            'actual_batch_qty': 7,
            'actual_qty': 2,
            'allow_zero_valuation_rate': 5,
            'amount': 140,
            'base_amount':100,
         }
      ]
test={}

我很担心,但它总是采用最后一个字典值

for data in items:
   
    test['actual_batch_qty'] = data['actual_batch_qty']
    test['amount']=data['base_amount']
        
print(test) 

输出:

{'actual_batch_qty': 7, 'amount': 100}

预期输出:

[{'actual_batch_qty': 5, 'amount': 80.0},{'actual_batch_qty': 7, 'amount': 100}]

【问题讨论】:

  • 预期的输出不是有效的 Python
  • @gold_cy 为什么无效?
  • 因为你所描述的是一个充满字典的集合,这是无效的,因为字典不是可散列的

标签: python dictionary


【解决方案1】:

看来你想要一个嵌套的字典。在您的情况下,您应该使用字典列表,但仍然可以通过添加顶级键来制作嵌套字典:

test={}

for i, data in enumerate(items):

    test[str(i)] = { 'actual_batch_qty': data['actual_batch_qty'], 'amount': data['base_amount'] }
    
print(test) 

输出:

{'0': {'actual_batch_qty': 5, 'amount': 80.0}, '1': {'actual_batch_qty': 7, 'amount': 100}}

循环遍历它:

for k,v in test.items():
    #stuff
    pass

【讨论】:

  • 那么如何循环这个输出呢?
  • 是的,如果继续使用 new_list=[] for k,v in test.items(): new_list.append(v) 将达到预期的输出非常感谢。
【解决方案2】:

UPD:问题已编辑,因此下面的答案无关紧要

使用defaultdict

from collections import defaultdict


items=[{'actual_batch_qty':5,
            'actual_qty': 6,
           'allow_zero_valuation_rate': 4,
             'amount': 80.0,
            'base_amount':80.0,
             },
             {'actual_batch_qty': 7,
               'actual_qty': 2,
               'allow_zero_valuation_rate': 5,
               'amount': 140,
                 'base_amount':100,
                }]

test = defaultdict(list)

for data in items:
    test['actual_batch_qty'].append(data['actual_batch_qty'])
    test['weigth'].append(data['total_weight'])

print(test) 

【讨论】:

  • 这个输出:defaultdict(, {'actual_batch_qty': [5, 7], 'amount': [80.0, 100]}) 我需要每个键与它的值配对连钥匙都重复了
  • python 中的dict是键:值对。您打算如何从预期输出中检索值?如果按索引 - 您可以创建字典列表。如果按键 - 您应该为每个嵌套字典创建一个键
  • 我需要将输出动态追加到字典列表
猜你喜欢
  • 2023-03-30
  • 2015-08-19
  • 2018-09-28
  • 2014-12-24
  • 1970-01-01
  • 2014-04-27
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多