Getting list length as values ​​in a dictionary in Python 2.7

I have two lists and a 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 element to be changed from my dictionary, i.e. the length of the value for the key. Looking at help('dict') , I could only find a function to return the number of keys, i.e. dict.__len__() . I tried the Java method (hoping it might work), i.e. len(dict.items()[0]) , but it evaluates to 2 .

I intend to find this:
Value length for the first key: 4
Value length for second key: 3

when lists are part of a dictionary, and not as separate lists, if their length is len(list) .

Any suggestions would be very helpful.

+7
source share
3 answers

dict.items() is a list containing all the keywords / values ​​of the dictionary, for example:

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

So, if you write len(dict.items()[0]) , then you request the length of the first tuple of this list of elements. Since tuples of dictionaries are always 2 tuples (pairs), you get a length of 2 . If you need the length of the value for this key, write:

 len(dict[key]) 

Aso: Avoid using standard type names (e.g. str , dict , set , etc.) as variable names. Python does not complain, but it hides type names and can lead to unexpected behavior.

+14
source

You can do this using dict understanding , 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 also, by the way, almost worked, but rather rather fearless. You 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 
+2
source
 >>>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] 
+2
source

All Articles