Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 576
ZHICHU ZHENG Avatar asked Jan 18 '17 13:01

ZHICHU ZHENG


People also ask

Can dictionary values be dictionary Python?

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.


2 Answers

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.

like image 199
Willem Van Onsem Avatar answered Oct 30 '22 00:10

Willem Van Onsem


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.

like image 25
Mohammad Yusuf Avatar answered Oct 30 '22 01:10

Mohammad Yusuf