假设我有以下内容:
c = {('jack','jones'): 1,
('jane','doe'): 2,
('mike','jones'): 3,
('jerry','doe'): 4,
('mary','jones'): 2}
如何重新映射此字典,以创建以下字典,其中姓氏用作键,而不是姓和名:
{('jones',): 6, ('doe',): 6}
新字典中的值是原始字典中该姓氏的值之和。
答案 0 :(得分:2)
您可以简单地遍历项目并继续添加计数:
c = {('jack','jones'): 1, ('jane','doe'): 2, ('mike','jones'): 3, ('jerry','doe'): 4,('mary','jones'): 2}
c_new = {}
for k, v in c.items():
c_new[k[1:]] = c_new.setdefault(k[1:], 0) + v
c_new
# {('doe',): 6, ('jones',): 6}