Talar
Talar

Reputation: 53

How can i know the number of elements in a dictionary?

I know that len(dict) would give the number of keys but what i want is this

 mydict = {
    'a': [[2,4], [5,6]],
    'b': [[1,1], [1,7,9], [6,2,3]],
    'c': [['a'], [4,5]],
}

The number i want in this case is 7, 7 being the number of elements in 'a' + number of elements in 'b' + number of elements in 'c'

Upvotes: 0

Views: 6447

Answers (3)

Andrea Fioraldi
Andrea Fioraldi

Reputation: 98

Your code is not a valid python dictionary.

This is a valid dictionary:

dict = {
        'a': ([2,4],[5,6]),
        'b': ([1,1],[1,7,9],[6,2,3]),
        'c': ([a],[4,5])
}

Use tuples to group multi-value items with fixed size (they have better performance than lists).

The answer to the question, using the correct dictionary, is

sum([len(e) for e in dict.values()])

Upvotes: 0

Priya Jain
Priya Jain

Reputation: 830

Please correct your example, it is not valid python dict.

I assumed that against every key you have list of lists.

dict = {
        'a': [[2,4],[5,6]],
        'b': [[1,1],[1,7,9],[6,2,3]],
        'c': [[3],[4,5]]
}

Your answer:

print sum (len(element) for element in dict.values());

Upvotes: 2

khelwood
khelwood

Reputation: 59186

Given a dictionary

mydict = {
    'a': [[2,4], [5,6]],
    'b': [[1,1], [1,7,9], [6,2,3]],
    'c': [['a'], [4,5]],
}

You can get the sum of the lengths of each value using

sum(map(len, mydict.values()))

Upvotes: 4

Related Questions