创建最佳的数据结构python

时间:2015-04-24 10:13:28

标签: python dictionary data-structures

我交叉引用两个共享6个公共字段的数据源。这个想法是文件1中的营销成本被分割出文件2中的销售交易。我已经写了一种方法来从第一个文件构建数据结构,以便第二个文件可以快速访问它,但它对我来说似乎不太嗜好。我有兴趣就是否有人认为可以用更好的方式撰写来获得一些意见和建议。

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)

1 个答案:

答案 0 :(得分:2)

这些4行try / except块中的每一个都可以使用setdefault替换为1行:

  

setdefault(key[, default])

     
      
  • 如果 key 在字典中,则返回其值。如果没有,请插入值为 default key 并返回 default 默认默认为None
  •   

所以这个:

cost_matrix[period].setdefault(territory, {})

......相当于:

try:
    cost_matrix[period][territory]
except KeyError:
    cost_matrix[period][territory]={}

除了你可以在一个更大的表达中使用它,这意味着理论上如果你愿意,你可以将整个事物变成一个巨大的表达式,虽然我不确定我会这样做。

您可以使用递归defaultdict进一步简化操作。 defaultdict基本上只是一个dict,它通过自动设置默认来处理丢失的密钥,而递归的一个defaultdict使用另一个dict而不是普通的setdefault。 (你仍然需要一个0或者只需要在结尾处使用普通键分配来处理默认的_make_defaultdict = lambda: defaultdict(_make_defaultdict) recursive_defaultdict = defaultdict(_make_defaultdict) cost_matrix = recursive_defaultdict() 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) 而不是另一个dict ......)

像这样:

KeyError

但是,请注意,这意味着您永远不会在代码中的任何其他地方获得setdefault。如果这是不可接受的,那么坚持使用dict。 (虽然如果你基本上构建了dict,然后使用它,你只需通过递归复制它就可以将它“冻结”成普通的CacheEntry[file:/C:/Users/User/workspace/SearchAlgorithms/bin/Main.jar]: updateAvailable=false,lastModified=Fri Apr 24 15:09:46 IST 2015,length=10095 Missing Permissions manifest attribute in main jar: file:/C:/Users/User/workspace/SearchAlgorithms/bin/Main.jar java.io.FileNotFoundException: dataProduct.csv (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at Main.init(Main.java:39) at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.init(Unknown Source) at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source) at java.lang.Thread.run(Unknown Source) java.io.FileNotFoundException: dataLocation.csv (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at Main.init(Main.java:45) at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.init(Unknown Source) at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Java Plug-in 10.79.2.15 Using JRE version 1.7.0_79-b15 Java HotSpot(TM) Client VM User home directory = C:\Users\User 。)

相关问题