Home > Back-end >  How do extract query-like results from a nested dictionary in Python?
How do extract query-like results from a nested dictionary in Python?

Time:06-26

I have a relatively simple nested dictionary as below:

emp_details = {
    'Employee': {
        'jim': {'ID':'001', 'Sales':'75000', 'Title': 'Lead'}, 
        'eva': {'ID':'002', 'Sales': '50000', 'Title': 'Associate'}, 
        'tony': {'ID':'003', 'Sales': '150000', 'Title': 'Manager'}
    }
}

I can get the sales info of 'eva' easily by:

print(emp_details['Employee']['eva']['Sales'])

but I'm having difficulty writing a statement to extract information on all employees whose sales are over 50000.

CodePudding user response:

You can't use one statement because the list initializer expression can't have an if without an else.

Use a for loop:

result = {} # dict expression
result_list = [] # list expression using (key, value)
for key, value in list(emp_details['Employee'].items())): # iterate from all items in dictionary
    if int(value['Sales']) > 50000: # your judgement
        result[key] = value # add to dict
        result_list.append((key, value)) # add to list
print(result)
print(result_list)
# should say:
'''
{'jim': {'ID':'001', 'Sales':'75000', 'Title': 'Lead'}, 'tony': {'ID':'003', 'Sales': '150000', 'Title': 'Manager'}}
[('jim', {'ID':'001', 'Sales':'75000', 'Title': 'Lead'}), ('tony', {'ID':'003', 'Sales': '150000', 'Title': 'Manager'})]
'''

CodePudding user response:

Your Sales is of String type.

Therefore, we can do something like this to get the information of employees whose sales are over 50000 : -

If you just want to get the information : -

emp_details={'Employee':{'jim':{'ID':'001', 'Sales':'75000', 'Title': 'Lead'}, \
                         'eva':{'ID':'002', 'Sales': '50000', 'Title': 'Associate'}, \
                         'tony':{'ID':'003', 'Sales': '150000', 'Title': 'Manager'}
                         }}
                         
for emp in emp_details['Employee']:
    if int(emp_details['Employee'][emp]['Sales']) > 50000:
        print(emp_details['Employee'][emp])

It print outs to -:

{'ID': '001', 'Sales': '75000', 'Title': 'Lead'}
{'ID': '003', 'Sales': '150000', 'Title': 'Manager'}
  • Related