I have a list in Python
and it's a dictionary contains a dictionary.
{'METTS MARK': {'salary': 365788, 'po': 1}, 'HARRY POTTER':{'salary': 3233233, 'po': 0}
How do I calculate the number of records with 'po' = 1
?
I tried this:
sum = 0
for key, values in DIC:
if values[po] == 1:
sum = sum + 1
But it returns: too many values to unpack
Thanks in advance
Dictionaries in PythonAlmost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions.
You can simply use sum
and sum over the condition:
total = sum(values.get('po') == 1 for values in DIC.values())
which is equivalent to (as @VPfB says):
total = sum (1 for item in DIC.values() if item.get('po') == 1)
but the latter is a bit less efficient.
You should also use 'po'
instead of po
since it is a string, and you better use .get('po')
since this guarantees that it will work if 'po'
is not part of every dictionary.
I think you forgot to use .items()
in your for
loop. By iterating over the dictionary, you iterate over the keys and in this case, you cannot unpack your keys into tuples with two elements.
Nevertheless using a generator, this will be more memory efficient (probably faster as well) and it is clean code. Furthermore by iterating directly over the .values
instead of the .items
one expects an increase in performance because one saves on packing and unpacking.
You can get it like this:
a = {
'METTS MARK': {'salary': 365788, 'po': 1},
'HARRY POTTER': {'salary': 3233233, 'po': 0}
}
print(len([b for b in a.values() if b.get('po')==1]))
Output:
1
Here we are creating a list of dictionaries where the key po==1
. And then we calculate the length of the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With