[Community wiki, because it's a little tangential.]
When you're processing tabular data in Python, you should consider the pandas
library. The operation you want to perform is a groupby sum, and that's easily done in two lines:
df = pd.read_csv("factories.csv")
by_factory = df.groupby("Factory")["Cost"].sum()
which produces a Series
object you can index into like a dictionary:
>>> by_factory
Factory
Bali 32
Denver 8
Sydney 25
Name: Cost, dtype: int64
>>> by_factory["Bali"]
32
Update, using the updated data-- if you also want to handle Cost_Type
, you have several options. One is to select only the rows with Cost_Type == 1:
>>> df[df.Cost_Type == 1]
Factory Cost Cost_Type
1 Sydney 21 1
3 Denver 8 1
4 Bali 9 1
[3 rows x 3 columns]
>>> df[df.Cost_Type == 1].groupby("Factory")["Cost"].sum()
Factory
Bali 9
Denver 8
Sydney 21
Name: Cost, dtype: int64
or you can expand the groupby and group on both Factory
and Cost_Type
simultaneously:
>>> df.groupby(["Cost_Type", "Factory"])["Cost"].sum()
Cost_Type Factory
0 Bali 23
1 Bali 9
Denver 8
Sydney 21
2 Sydney 4
Name: Cost, dtype: int64