简体   繁体   中英

How can I get lengths of values for each of the key in a dictionary?

Below is my dictionary. I am trying to calculate lengths of values for each key.Can somebody please help me?

My_data = {1: [1450.0, -80.0, 840.0, -220.0, 630.0, 780.0, -1140.0], 2: [1450.0, -80.0, 840.0, -220.0, 630.0, 780.0, -1140.0],3:[ 720.0, -230.0, 460.0, 220.0, 710.0, -460.0, 90.0] }

This is what I have tried:

for k, v in My_data .iteritems():
        print k, len(v)

The desired output is [1:len(values), 2:len(values)]

If you just want the lengths, you can use a list comprehension

>>> [len(v) for v in My_data.values()]
[7, 7, 7]

If you want them associated with each key

>>> [tuple((k, len(v))) for k,v in My_data.items()]
[(1, 7), (2, 7), (3, 7)]

Or as a new dict

>>> {k: len(v) for k,v in My_data.items()}
{1: 7, 2: 7, 3: 7}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM