2017-03-07 65 views
0

我要過濾特定部門的工資和總結,我已經做了上半場,但添加這些工資,任何一個可以通過查看下面的代碼表明....如何總結選擇性字典值

chennai = {"name": "Kumar", "Department": "Sales",  "Age": 39,"Salary": 20} 
mumbai = {"name": "Suresh","Department": "Finance", "Age": 53,"Salary": 35} 
delhi = {"name": "Babu", "Department": "QC",  "Age": 28,"Salary": 10} 
kolkata = {"name": "Satish","Department": "Production","Age": 34,"Salary": 15} 
madurai = {"name": "Dev", "Department": "Management","Age": 45,"Salary": 23} 
hyderabad = {"name": "Rani", "Department": "Marketing", "Age": 46,"Salary": 25} 
bengalore = {"name": "Devi", "Department": "Production","Age": 24,"Salary": 5} 
cochin = {"name": "Sarath","Department": "Production","Age": 26,"Salary": 12} 
jaipur = {"name": "Senu", "Department": "Production","Age": 25,"Salary": 8} 
shimla = {"name": "Kumari","Department": "Management","Age": 37,"Salary": 20} 
lucknow = {"name": "Sanjay","Department": "Marketing", "Age": 52,"Salary": 30} 

employ = [chennai,mumbai,delhi,kolkata,madurai,hyderabad,bengalore,cochin,jaipur,shimla,lucknow] 

#Finding Production unit salary expenditure 
for x in employ: 
    sums = 0 
    if x ["Department"] == 'Production': 
     print x["Salary"] 

回答

0

如果你想要一個班輪

result = sum(d.get("Salary", 0) for d in employ if d.get("Department") == "Production") 

也可以總和爲多個。

departments = {"Production", "Marketing"} 
result = sum(d.get("Salary", 0) for d in employ if d.get("Department") in departments) 
0

我會建議使用熊貓(http://pandas.pydata.org/

import pandas as pd 
# Creating the dataframe 
dataset = pd.DataFrame(employ) 
print (dataset) 
#Out[3]: 
# Age Department Salary name 
#0 39  Sales  20 Kumar 
#1 53  Finance  35 Suresh 
#2 28   QC  10 Babu 
#3 34 Production  15 Satish 
#4 45 Management  23  Dev 
#5 46 Marketing  25 Rani 
#6 24 Production  5 Devi 
#7 26 Production  12 Sarath 
#8 25 Production  8 Senu 
#9 37 Management  20 Kumari 
#10 52 Marketing  30 Sanjay 

# Production Salary 
dataset1 = dataset[dataset['Department'] == 'Production'].Salary 
print (dataset1) 
#Out[6]: 
#3 15 
#6  5 
#7 12 
#8  8 
#Name: Salary, dtype: int64 

# Sum Salaries 
dataset2 = dataset[dataset['Department'] == 'Production'].Salary.sum() 
print (dataset2) 
# 40 

上面的代碼看起來不那麼漂亮,但大熊貓是非常強大的。 這裏是你如何能得到按部門工資總額:

dataset3 = dataset.groupby('Department').sum()['Salary'] 
print (dataset3) 
#Out[8]: 
#Department 
#Finance  35 
#Management 43 
#Marketing  55 
#Production 40 
#QC   10 
#Sales   20 
#Name: Salary, dtype: int64 
0

如果你不想使用熊貓試試這個,

from collections import defaultdict 
salary = defaultdict(int) 
# for specific departments 
required_departments = ["Production"] 
for i in employ: 
    if i["Department"] in required_departments: 
     salary[i["Department"]] += i["Salary"] 
print(salary) 
# for all departments 
salary = defaultdict(int) 
for i in employ: 
    salary[i["Department"]] += i["Salary"] 

print(salary)