简体   繁体   中英

Retrieve a value of a key based on another value(of key) in the list of dictionaries

question about list of dicts: """this is the list of dicts for employees and salaries(pls note this is an example and want this in python memory instead of any other form such as #sql table)"""

complete_emp_list = [{'emp_name':'abc','salary':1000}, {'emp_name':'def','salary':2000},{'emp_name':'xyz','salary':3000}]

Question: how do I retrieve the salary for a given emp name as part of below query.

cursor.execute("SELECT emp_name, {%d}*0.1 AS ret_bonus FROM employee_resigned", salary)

Please note I don't want to run this query for all the employees, but only for those in the employee_resigned table (1 or 2 emp) and get the salary from python list(using only list of dicts in the format given above) (this is very hypothetical example :))

Just build a dictionary that maps employee names to their salaries:

salaries = {d['emp_name']: d['salary'] for d in complete_emp_list}

Then it's a simple matter of indexing: salaries[employee_name] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM