Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 207
Srikanth Suresh Avatar asked Jun 16 '13 11:06

Srikanth Suresh


People also ask

How do you get the length of a list in a dictionary?

To calculate the length of a dictionary, we can use the Python built-in len() method. The len() method returns the number of keys in a Python dictionary.

Can a Python dictionary have a list as a value?

It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.

How do I get the length of a list in Python?

Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.

What is the use of Len () in dictionary?

Python dictionary method len() gives the total length of the dictionary. This would be equal to the number of items in the dictionary.


2 Answers

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.

like image 135
Alexander Tobias Bockstaller Avatar answered Dec 19 '22 12:12

Alexander Tobias Bockstaller


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
like image 35
Tim Pietzcker Avatar answered Dec 19 '22 10:12

Tim Pietzcker