小编PRO*_*COL的帖子

将键的所有其他值设置为0(第一个值除外)的Python方法

我有一个嵌套的字典:

nested_dict = { 
               19376: {
                      'key1': 'SAL/2018/4207', 
                      'premium_due_amount': 1162239.98,
                      }, 
               19377: {'key1': 'SAL/2018/4207', 
                       'premium_due_amount': 1162239.98,
                      }, 
               19378: {
                       'key1': 'SAL/2018/4207', 
                       'premium_due_amount': 1162239.98,
                      } 
              }
Run Code Online (Sandbox Code Playgroud)

在每本字典中,我都有一个key1和一个premium_due_amount

由于key1已在第一个字典中设置,因此我想将除第一个字典外的所有其他premium_due_amount的值更改为0。

预期产量

nested_dict = { 
               19376: {
                      'key1': 'SAL/2018/4207', 
                      'premium_due_amount': 1162239.98,
                      }, 
               19377: {'key1': 'SAL/2018/4207', 
                       'premium_due_amount': 0,
                      }, 
               19378: {
                       'key1': 'SAL/2018/4207', 
                       'premium_due_amount': 0,
                      } 
              }
Run Code Online (Sandbox Code Playgroud)

当前解决方案:

key1_list = [] 
for key, vals in nested_dict.items(): 
   if vals['key1'] in key1_list: 
       vals.update({'premium_due_amount': 0}) 
   key1_list.append(vals['key1'])
Run Code Online (Sandbox Code Playgroud)

请提出一种更简化的Python方式来实现此目的。

python dictionary list python-3.x

5
推荐指数
0
解决办法
43
查看次数

标签 统计

dictionary ×1

list ×1

python ×1

python-3.x ×1