Reputation: 23
I have an enormous set of data about people store in a nested dictionary.
The outer dictionary has the key is the name of a person and the value is another dictionary contains all information about that person (features, such as email, phone, number, salary, ...). The inner dict keys are the features names (so 'email' and so on), and the value is the value of the feature (so '[email protected]'
).
I know that all people have the same number of features. How can I count how many features there are?
When I do this, I only get the number of people:
print(len(enron_data))
Upvotes: 1
Views: 1023
Reputation: 1124988
If you need the length of just one of the values of the outer dictionary, just pick the 'first' value in iteration order. For dictionaries the order is either 'arbitrary' or insertion order, but if all your dictionaries have the same number of keys, it doesn't matter which one you pick.
To get the 'first', turn dict.values()
into an iterator with iter()
and call next()
on the result:
one_value = next(iter(enron_data.values())) # *one* of the values
number_of_features = len(one_value)
If next()
and iter()
look scary, you can also use a for
loop and break
to end the loop after the first iteration:
for value in enron_data.values():
number_of_features = len(one_value)
break
I'm assuming you are using Python 3 here. If you are using Python 2, use enron_data.itervalues()
instead of enron_data.values()
, otherwise you create a big new list object for all the values first. That's a waste of memory and CPU time, really.
Upvotes: 3