Python 删除列表字典中的类似值
我有以下以2dlist作为值的字典:Python 删除列表字典中的类似值,python,list,dictionary,Python,List,Dictionary,我有以下以2dlist作为值的字典: dictionary = {Hello: [[2001,45], [2003, 52], [2001, 6], [2002, 90]], Jello: [[2009,3], [2003, 4], [2009, 17], [2009,1], [2009,1],[2002, 11]], Cello: [[2001,5], [2001, 2], [2001, 6], [2001, 3]]} 我想更改字典,以
dictionary = {Hello: [[2001,45], [2003, 52], [2001, 6], [2002, 90]],
Jello: [[2009,3], [2003, 4], [2009, 17], [2009,1], [2009,1],[2002, 11]],
Cello: [[2001,5], [2001, 2], [2001, 6], [2001, 3]]}
我想更改字典,以便将键内具有相同年份的所有列表的值相加
因此,每年每个键只应显示一次
使字典看起来像这样:
dictionary = {Hello: [[2001,51], [2003, 52], [2002, 90]],
Jello: [[2009,22], [2003, 4], [2002, 11]],
Cello: [[2001,16]]}
我该怎么做?请提供帮助。我认为您的思路是正确的,一个易于实现的解决方案可能是创建一个
合并功能,并在中使用它:
def pretty_print_simple_dict(d):
print("{")
for key, value in d.items():
print(f"\t{key}: {value}")
print("}")
def merge_years(lst):
year_counts = {}
for year, count in lst:
year_counts[year] = year_counts.get(year, 0) + count
return [[year, total] for year, total in year_counts.items()]
d = {
'Hello': [[2001, 45], [2003, 52], [2001, 6], [2002, 90]],
'Jello': [[2009, 3], [2003, 4], [2009, 17], [2009, 1], [2009, 1],
[2002, 11]],
'Cello': [[2001, 5], [2001, 2], [2001, 6], [2001, 3]]
}
d = {k: merge_years(v) for k, v in d.items()}
pretty_print_simple_dict(d)
输出:
{
Hello: [[2001, 51], [2003, 52], [2002, 90]]
Jello: [[2009, 22], [2003, 4], [2002, 11]]
Cello: [[2001, 16]]
}
我该怎么做?请帮忙。有具体问题吗?请看,。请从下一页重复和。“演示如何解决此编码问题?”与堆栈溢出无关。您必须诚实地尝试解决方案,然后询问有关实现的具体问题。堆栈溢出不是为了取代现有的教程和文档。非常感谢兄弟。您是否可以考虑在不导入库的情况下执行此操作?@unknownjumper你看:)