【问题标题】:python TypeError unhashable type: dict cant find the set to freeze [duplicate]python TypeError unhashable type:dict找不到要冻结的集合[重复]
【发布时间】:2014-11-07 03:47:02
【问题描述】:

我查看了以下链接以确定我应该在哪里冻结我的代码

TypeError: unhashable type: 'dict'

TypeError: unhashable type: 'dict', when dict used as a key for another dict

TypeError: unhashable type: 'dict' in python

def getPx (self, date, instrument, item = 'Adj Close', prices = None):
        ''' get a price for an instrument on a date from prices table'''

    prices = prices or self.prices
    import datetime
    import numpy as np

    if type ( instrument ) == np.ndarray: instrument = str ( instrument [ 0 ] )

    pricelist = [item.copy() for item in prices[instrument]]
    for item in pricelist:
        item['Date'] = datetime.datetime.strptime(item['Date'],"%Y-%m-%d")


    dates = map(lambda x: x['Date'],pricelist)
    eff_date = max([d for d in dates if d <= date])

    price = [price[item] for price in pricelist if price["Date"] == eff_date]

    return price

pricelist 是一个字典,但我似乎不知道要冻结什么。浪费了整个上午试图弄清楚为什么我不能从我的字典中得到特定日期的价格..

非常感谢任何帮助

编辑:

典型的示例价目表是

{'ABCD':{'Adj Close': '82.72',
   'Close': '86.06',
   'Date': '2013-09-19',
   'High': '86.90',
   'Low': '85.79',
   'Open': '86.86',
   'Volume': '18700'},
  {'Adj Close': '83.67',
   'Close': '87.05',
   'Date': '2013-09-18',
   'High': '87.75',
   'Low': '85.18',
   'Open': '85.49',
   'Volume': '30900'},
  {'Adj Close': '82.48',
   'Close': '85.81',
   'Date': '2013-09-17',
   'High': '85.85',
   'Low': '85.02',
   'Open': '85.12',
   'Volume': '14700'},
  {'Adj Close': '81.43',
   'Close': '84.72',
   'Date': '2013-09-16',
   'High': '86.36',
   'Low': '84.42',
   'Open': '86.18',
   'Volume': '4700'},
  {'Adj Close': '82.16',
   'Close': '85.48',
   'Date': '2013-09-13',
   'High': '86.31',
   'Low': '85.12',
   'Open': '85.98',
   'Volume': '205000'},
  {'Adj Close': '82.10',
   'Close': '85.42',
   'Date': '2013-09-12',
   'High': '86.60',
   'Low': '85.08',
   'Open': '86.33',
   'Volume': '16000'},
  {'Adj Close': '82.15',
   'Close': '85.47',
   'Date': '2013-09-11',
   'High': '85.47',
   'Low': '84.47',
   'Open': '85.14',
   'Volume': '9700'}}

【问题讨论】:

  • 循环价格表中的类型(项目)是什么?
  • 嗨@user3。 for 循环中的类型(项目)是

标签: python dictionary


【解决方案1】:

在您的 price = [price[item] for price in pricelist if price["Date"] == eff_date] 行中,您使用的是 item,它以前在 for 循环中使用:

for item in pricelist: item['Date'] = datetime.datetime.strptime(item['Date'],"%Y-%m-%d")

item 是一个字典,您不能将它用作price 字典中的键。

【讨论】:

  • 谢谢@Rikka 我相信你昨天救了我的理智..
  • 不客气。我很高兴能帮上忙。:p
【解决方案2】:

您有 item 的嵌套字典。您需要以item['ABCD']['Date'] 而不是item['Date'] 在价格表forloop 中访问数据。

因此,如下更改代码即可:

for item in pricelist:
    for k in item:
        item[k]['Date'] = datetime.datetime.strptime(item[k]['Date'],"%Y-%m-%d")

【讨论】:

    猜你喜欢
    • 2015-02-11
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2020-05-11
    • 2022-08-11
    • 2018-06-04
    • 1970-01-01
    • 2023-02-05
    相关资源
    最近更新 更多