Obtaining length of list as a value in dictionary in Python 2.7

倖福魔咒の 提交于 2021-02-18 22:28:09

问题


I have two lists and dictionary as follows:

>>> var1=[1,2,3,4]
>>> var2=[5,6,7]
>>> dict={1:var1,2:var2}

I want to find the size of the mutable element from my dictionary i.e. the length of the value for a key. After looking up the help('dict'), I could only find the function to return number of keys i.e. dict.__len__(). I tried the Java method(hoping that it could work) i.e. len(dict.items()[0]) but it evaluated to 2.

I intend to find this:
Length of value for first key: 4
Length of value for second key: 3

when the lists are a part of the dictionary and not as individual lists in case their length is len(list).

Any suggestions will be of great help.


回答1:


dict.items() is a list containing all key/value-tuples of the dictionary, e.g.:

[(1, [1,2,3,4]), (2, [5,6,7])]

So if you write len(dict.items()[0]), then you ask for the length of the first tuple of that items-list. Since the tuples of dictionaries are always 2-tuples (pairs), you get the length 2. If you want the length of a value for a given key, then write:

len(dict[key])

Aso: Try not to use the names of standard types (like str, dict, set etc.) as variable names. Python does not complain, but it hides the type names and may result in unexpected behaviour.




回答2:


You can do this using a dict comprehension, for example:

>>> var1 = [1,2,3,4]
>>> var2 = [5,6,7]
>>> d = {1:var1, 2:var2}
>>> lengths = {key:len(value) for key,value in d.iteritems()}
>>> lengths
{1: 4, 2: 3}

Your "Java" method would also nearly have worked, by the way (but is rather unpythonic). You just used the wrong index:

>>> d.items()
[(1, [1, 2, 3, 4]), (2, [5, 6, 7])]
>>> d.items()[0]
(1, [1, 2, 3, 4])
>>> len(d.items()[0][1])
4



回答3:


>>>for k,v in dict.iteritems():
   k,len(v)

ans:-

(1, 4)
(2, 3)

or

>>>var1=[1,2,3,4]
>>>var2=[5,6,7]
>>>dict={1:var1,2:var2}

ans:-

>>>[len(v) for k,v in dict.iteritems()]
[4, 3]


来源:https://stackoverflow.com/questions/17133000/obtaining-length-of-list-as-a-value-in-dictionary-in-python-2-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!