ZHICHU ZHENG
ZHICHU ZHENG

Reputation: 311

How to query values in a dictionary of a dictionary in python?

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

Upvotes: 5

Views: 18945

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477533

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.

Upvotes: 8

Mohammad Yusuf
Mohammad Yusuf

Reputation: 17074

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.

Upvotes: 2

Related Questions