Home > Net >  Count the values per key in tuples
Count the values per key in tuples

Time:12-28

I have an input data like this:

('Volvo', [23880.0, 10200.0])
('SsangYong', [11400.0])
('Fiat', [7800.0])

I would like to identify the counts for each key.

I have tried multiple ways as below but it did not work.

for k, v in kvdata.items():
    (k, count) = (k, count(v))
    return [(k, count)]

The desired output should be:

('Volve', 2)
('SsangYong', 1)
('Fiat', 1)

CodePudding user response:

Hey I got the point.

t = (('Volvo', [23880.0, 10200.0]),
('SsangYong', [11400.0]),
('Fiat', [7800.0]))

for (k,v) in t:
    print(k,len(v))

Output is:

Volvo 2
SsangYong 1
Fiat 1

CodePudding user response:

The solution to your question is to wrap all cars inside a variable and modify your problematic for loop.

You have to enclose all the cars inside a variable like this:

car brand = (('Volvo', [23880.0, 10200.0]), ('SsangYong', [11400.0]), ('Fiat', [7800.0]))

Next you need to change something in your cycle. You can simplify it like this:

for (k,v) in car brand:
    print(k,len(v))

The output will be like yours, but without round brackets, commas, and quotes

COMPLETE SOLUTION CODE

car brand = (('Volvo', [23880.0, 10200.0]), ('SsangYong', [11400.0]), ('Fiat', [7800.0]))

for (k,v) in car brand:
    print(k,len(v))
  • Related