python: count values of dictionary

100 Views Asked by At

I'm working with python and I need to find in a dictionary how many values each key has. this is my dictionary:

 {2: [(1, 1)], 3: [(2, 1), (2, 1)], 4: [(1, 3), (3, 1), (3, 1)], 5: [(1, 4), (2, 3), (2, 3), (4, 1)], 6: [(1, 5), (2, 4), (2, 4), (3, 3), (3, 3)], 7: [(1, 6), (2, 5), (2, 5), (3, 4), (3, 4), (4, 3)], 8: [(2, 6), (2, 6), (3, 5), (3, 5), (4, 4)], 9: [(1, 8), (3, 6), (3, 6), (4, 5)], 10: [(2, 8), (2, 8), (4, 6)], 11: [(3, 8), (3, 8)], 12: [(4, 8)]}

I need to find how many values there are for each key: so it will be like:

{2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1}

I've tried to make it work for a long time thanks in advance

1

There are 1 best solutions below

0
On BEST ANSWER

Not sure if this is what you're looking for?

def getcountvalue(d):
    newdict = {}
    for key, value in d.items():
        newdict[key] = len(value)
    return newdict

d = {2: [(1, 1)], 3: [(2, 1), (2, 1)], 4: [(1, 3), (3, 1), (3, 1)], 5: [(1, 4), (2, 3), (2, 3), (4, 1)], 6: [(1, 5), (2, 4), (2, 4), (3, 3), (3, 3)], 7: [(1, 6), (2, 5), (2, 5), (3, 4), (3, 4), (4, 3)], 8: [(2, 6), (2, 6), (3, 5), (3, 5), (4, 4)], 9: [(1, 8), (3, 6), (3, 6), (4, 5)], 10: [(2, 8), (2, 8), (4, 6)], 11: [(3, 8), (3, 8)], 12: [(4, 8)]}
newd = getcountvalue(d)