Python 如何找到字典值的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26190160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find length of dictionary values
提问by Andre
I am pretty new to all of this so this might be a noobie question.. but I am looking to find length of dictionary values... but I do not know how this can be done.
我对这一切都很陌生,所以这可能是一个菜鸟问题..但我正在寻找字典值的长度......但我不知道如何做到这一点。
So for example,
例如,
d = {'key':['hello', 'brave', 'morning', 'sunset', 'metaphysics']}
I was wondering is there a way I can find the lenor number of itemsof the dictionary value.
我想知道有没有办法可以找到字典值的len或项目数。
Thanks
谢谢
采纳答案by mgilson
Sure. In this case, you'd just do:
当然。在这种情况下,您只需执行以下操作:
length_key = len(d['key']) # length of the list stored at `'key'` ...
It's hard to say why you actually want this, but, perhaps it would be useful to create another dict that maps the keys to the length of values:
很难说为什么你真的想要这个,但是,也许创建另一个将键映射到值长度的字典会很有用:
length_dict = {key: len(value) for key, value in d.items()}
length_key = length_dict['key'] # length of the list stored at `'key'` ...
回答by squiguy
To find all of the lengths of the values in a dictionary you can do this:
要在字典中查找值的所有长度,您可以执行以下操作:
lengths = [len(v) for v in d.values()]
回答by Lundy
Lets do some experimentation, to see how we could get/interpret the length of different dict/array values in a dict.
让我们做一些实验,看看我们如何获取/解释字典中不同字典/数组值的长度。
create our test dict, see list and dict comprehensions:
创建我们的测试字典,请参阅列表和字典理解:
>>> my_dict = {x:[i for i in range(x)] for x in range(4)}
>>> my_dict
{0: [], 1: [0], 2: [0, 1], 3: [0, 1, 2]}
Get the length of the value of a specific key:
获取特定键值的长度:
>>> my_dict[3]
[0, 1, 2]
>>> len(my_dict[3])
3
Get a dict of the lengths of the values of each key:
获取每个键的值长度的字典:
>>> key_to_value_lengths = {k:len(v) for k, v in my_dict.items()}
{0: 0, 1: 1, 2: 2, 3: 3}
>>> key_to_value_lengths[2]
2
Get the sum of the lengths of all values in the dict:
获取字典中所有值的长度总和:
>>> [len(x) for x in my_dict.values()]
[0, 1, 2, 3]
>>> sum([len(x) for x in my_dict.values()])
6
回答by SHAIK GOUSIA
d={1:'a',2:'b'}
sum=0
for i in range(0,len(d),1):
sum=sum+1
i=i+1
print i
OUTPUT=2
输出=2
回答by Siddhi Jha
Let dictionary be : dict={key:['value1','value2']}
If you know the key :print(len(dict[key]))
else : val=[len(i) for i in dict.values()]print(val[0])# for printing length of 1st key value or length of values in keys if all keys have same amount of values.
让字典为:dict={key:['value1','value2']}
如果您知道密钥:print(len(dict[key]))
否则:val=[len(i) for i in dict.values()]print(val[0])# for printing length of 1st key value or length of values in keys if all keys have same amount of values.

