Warm tip: This article is reproduced from serverfault.com, please click

Delete similar values in dictionary of 2dlists

发布于 2020-11-28 02:38:48

I have the following dictionary with 2dlist as values:

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]]}

I want to change the dictionary so all lists with the same year within the key have their values added up.

So each year should only show up once per key.

Making the dictionary look like this:

dictionary = {Hello: [[2001,51], [2003, 52], [2002, 90]],

             Jello: [[2009,22], [2003, 4], [2002, 11]],

             Cello: [[2001,16]]}

How would I do this? Please help.

Questioner
unknownjumper
Viewed
0
Sash Sinha 2020-11-28 11:10:40

I think you are on the right track, one easy to implement solution could be to just create a merge_years function and use that within a dict_comprehension:

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)

Output:

{
    Hello: [[2001, 51], [2003, 52], [2002, 90]]
    Jello: [[2009, 22], [2003, 4], [2002, 11]]
    Cello: [[2001, 16]]
}