How to find length of dictionary values

后端 未结 6 1697
忘了有多久
忘了有多久 2020-12-13 18:24

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.

S

6条回答
  •  情歌与酒
    2020-12-13 18:41

    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
    

提交回复
热议问题