简体   繁体   English

如何获得字典中每个键的值长度?

[英]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)] 所需的输出是[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 或作为一个新的dict

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何计算嵌套字典中每个键的列表长度总和? - how to calculate the sum of list's lengths of each key in a nested dictionary? 如何通过读取.txt文件的每一行来将键值添加到字典中并更新值? - How can I add key values into a dictionary from reading in each line of a .txt file and update values? Pandas 和字典:如何获取每个键的所有唯一值? - Pandas and Dictionary: How to get all unique values for each key? 如何计算python字典每个键中不同值的平均值? - How can I calculate average of different values in each key of python dictionary? 如何将具有不同长度值的列表转换为字典? - How do I convert a list with values of different lengths into a dictionary? 我怎样才能 append 字典的每个键和值到列? - How can I append each key and value of dictionary to columns? 如何在不互相替换的情况下获得字典的多个值? - How can I get multiple values for my dictionary without them replacing each other? 如何获取不同字典中相同键的所有值,并且字典存储在列表中 - how can i get all the values for the same key in different dictionary and dictionaries are stored in a list 如何使用python从字典中获取特定键的值 - How can I get values from dictionary for particular key using python 如何用每个键的多个值反转字典? - How to invert dictionary with multiple values of each key?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM