我有一个嵌套的字典:
public final class R {
public static final class layout{
public static final int main_activity=0x7f0a0000;
public static final int login_activity=0x7f0a0001;
}
public static final class drawable{
public static final int ic_add=0x7f0a0000;
public static final int ic_edit=0x7f0a0001;
}
public static final class mimap{
public static final int ic_launcher=0x7f0b0000;
}
public static final class raw {
public static final int sound=0x7f0b0000;
}
}
在每本词典中,我都有一个 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': 1162239.98,
},
19378: {
'key1': 'SAL/2018/4207',
'premium_due_amount': 1162239.98,
}
}
当前解决方案:
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,
}
}
请提出一种更简化且更Python化的方法。
答案 0 :(得分:3)
IIUC,您希望将除最小键以外的所有值设置为0。这应该适用于任何python3.x,因为dict.keys()
返回了一个set- like 对象,您可以对其执行set操作。
for k in nested_dict.keys() - {min(nested_dict)}:
nested_dict[k]['premium_due_amount'] = 0
print (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}}