qualifier_2 = {'KKR' : {'Chris Lynn': 4,
'Sunil Narine': 10,
'Gautam Gambhir (c)': 12,
'Robin Uthappa (wk)': 1,
'Ishank Jaggi': 28,
'Colin Grandhomme': 0,
'Suryakumar Yadav': 31,
'Piyush Chawla': 2,
'Nathan Coulter-Nile': 6,
'Umesh Yadav': 2,
'Ankit Rajpoot': 4,
'Extra runs': 7,
'Total batted': 10},
'MI': {'Lendl Simmons': 3,
'Parthiv Patel (wk)': 14,
'Ambati Rayudu': 6,
'Rohit Sharma (c)': 26,
'Krunal Pandya': 45,
'Kieron Pollard': 9,
'Extra runs': 8,
'key-valueal batted': 6}
}
这是嵌套字典,我想删除某个键值对,并且想要所有分数的总和。
答案 0 :(得分:0)
我认为这是最快的解决方案,没有循环:
summ_KRR = sum(qualifier_2['KKR'].values()) # sum of 'KRR'
sum_all = sum(map(lambda x: sum(qualifier_2[x].values()),qualifier_2.keys())) # all sum
qualifier_2.pop('KKR', None) # delete 'KRR'
print('sum:{}'.format(summ_KRR))
print(qualifier_2)
答案 1 :(得分:0)
删除键/值对:
key_to_remove = 'Krunal Pandya'
for key in qualifier_2:
inner_dict = qualifier_2[key]
if key_to_remove in inner_dict:
del inner_dict[key_to_remove]
break
键值汇总:
total = sum([val for outer_key in qualifier_2
for __, val in qualifier_2[outer_key].items()])
测试删除:
import pprint
pprint.pprint(qualifier_2) # after removing 'Krunal Pandya'
输出:
{'KKR': {'Ankit Rajpoot': 4, 'Chris Lynn': 4, 'Colin Grandhomme': 0, 'Extra runs': 7, 'Gautam Gambhir (c)': 12, 'Ishank Jaggi': 28, 'Nathan Coulter-Nile': 6, 'Piyush Chawla': 2, 'Robin Uthappa (wk)': 1, 'Sunil Narine': 10, 'Suryakumar Yadav': 31, 'Total batted': 10, 'Umesh Yadav': 2}, 'MI': {'Ambati Rayudu': 6, 'Extra runs': 8, 'Kieron Pollard': 9, 'Lendl Simmons': 3, 'Parthiv Patel (wk)': 14, 'Rohit Sharma (c)': 26, 'key-valueal batted': 6}}
测试求和:
print(total) # with original qualifier_2
输出:
234