【发布时间】:2015-04-24 18:54:38
【问题描述】:
我正在交叉引用共享 6 个公共字段的两个数据源。这个想法是文件 1 中的营销成本被分配到文件 2 中的销售交易中。我已经编写了一种从第一个文件构建数据结构的方法,以便第二个文件可以快速访问它,但它似乎没有-对我来说是pythonic。我有兴趣就是否有人认为可以以更好的方式编写它获得一些意见和意见。
cost_matrix = {}
for line in marketing_costs:
line_date_object = time.strptime(line['date'], "%d/%m/%Y")
period = '%04d_%02d' % (line_date_object.tm_year, line_date_object.tm_mon)
territory = line['territory'].lower()
salesperson=line['salesperson'].lower()
customer_type = line['customer_type'].lower()
affiliate=line['affiliate'].lower()
product_group = line['product_group'].lower()
line_mktg_cost=line['mktg_cost']
try:
cost_matrix[period]
except KeyError:
cost_matrix[period]={}
try:
cost_matrix[period][territory]
except KeyError:
cost_matrix[period][territory]={}
try:
cost_matrix[period][territory][salesperson]
except KeyError:
cost_matrix[period][territory][salesperson]={}
try:
cost_matrix[period][territory][salesperson][customer_type]
except KeyError:
cost_matrix[period][territory][salesperson][customer_type]={}
try:
cost_matrix[period][territory][salesperson][customer_type][affiliate]
except KeyError:
cost_matrix[period][territory][salesperson][customer_type][affiliate]={}
try:
cost_matrix[period][territory][salesperson][customer_type][affiliate][product_group]
except KeyError:
cost_matrix[period][territory][salesperson][customer_type][affiliate][product_group]={}
cost_matrix[period][territory][salesperson][customer_type][affiliate][product_group]['mktg_cost']=0
cost_matrix[period][territory][salesperson][customer_type][affiliate][product_group]['mktg_cost']+=Decimal(line_mktg_cost)
【问题讨论】:
标签: python dictionary data-structures