TypeError:不可散列的类型:'dict'的逻辑的50%部分,其余的50%正常工作

我有本字典,会根据当前/实时市场数据不断更新。下面是我提到的字典,下面是更新字典的逻辑。

字典

trd_portfolio = {5633: {"Symbol": "acc","max_quantity": 10000,"Direction": "",'Orderid': 0,'Target_order': '','Target_order_id': 0},25601: {"Symbol": "AMARAJABAT",'Target_order_id': 0}
                 }

更新逻辑

def order_status(token,orderid,type):
    order_details = kite.order_history(orderid)
    for item in order_details:
        if item['status'] == "COMPLETE":
            if type == 'SELL':
                trd_portfolio[token]['Direction'] = "Down"
                trd_portfolio[token]['Target_order'] = "NO"
                print(trd_portfolio[token]['Direction'],trd_portfolio[token]['Target_order'])
                break
            elif type == 'BUY':
                trd_portfolio[token]['Direction'] = "Up"
                trd_portfolio[token]['Target_order'] = "NO"
                print(trd_portfolio[token]['Direction'],trd_portfolio[token]['Target_order'])
                break
        elif item['status'] == "REJECTED":
            print(trd_portfolio[token]['Direction'],trd_portfolio[token]['Target_order'])
            break
    else:
        time.sleep(1)
        order_status(token,type)

如果我使用值为order_status(5633,some_order_id,SELL)的值调用update逻辑方法,则字典将正确更新,并且可以继续进行操作。但是,如果我将方法称为order_status(5633,BUY),则会出现以下错误。

trd_portfolio[token]['Direction'] = "Up"
TypeError: unhashable type: 'dict'

为什么它在一个地方失败而在另一个地方工作,我看不出有什么区别。为什么它必须是可哈希的,因为我想整天不断更新字典。

xinfeifei1 回答:TypeError:不可散列的类型:'dict'的逻辑的50%部分,其余的50%正常工作

您怎么知道两个对象相等或不相等?

这很重要。如果我们写,

d[3] = 0
d[3] = 99

d[1] = 5
d[2] = 104

然后,99应该代替0。这是因为3 == 3。但是,104不应该替换5,因为1 != 2。但是,计算机如何知道字典键是否彼此相等?

考虑以下代码:

x = "apple"
y = "apple"
print(x == y)

输出为True。但是计算机如何知道两个字符串相等?好吧,它将字符串转换为数字,然后比较数字是否相等。见下文:

x = "apple"
y = "apple"
x_number = hash(x)
y_number = hash(y)
print(x_number)
print(y_number)

输出为:

1505705734
1505705734

假设您编写了自己的课程:

class XYCoodinate:
    def __init__(self,x,y):
        self.x = x
        self.y = y

计算机如何知道两个实例是否相等?除非您告诉计算机,否则计算机不知道两个XYCoodinates相等意味着什么。

xy1 = XYCoodinate(1,2)
xy2 = XYCoodinate(1,2)
print(xy1 == xy2)

尽管两个XYCoodinate看起来与人类相当,但相等性测试的输出为False。老实说,计算机不知道该怎么办。因此,默认行为如下:

def __eq__(lhs,rhs):
    # `lhs`...........`left-hand-side`
    # `rhs`...........`right-hand-side`
if `lhs` and `rhs` are two different labels for the same memory "hotel room"
    # if a hotel room contains 5 it contains 5,not both 2 and 5.
    # if you have two different names for the same hotel room,they must be equal
    return True
if `lhs` and `rhs` are two different memory "hotel room" numbers:
    # the hotel rooms might contain two copies the same data,the hotel rooms might not
    # However,unless it's something simply like an integer,# the computer doesn't know how to tell if they are equal or not.

计算机知道如何对整数和整数元组进行哈希处理,所以我们可以这样做:

class XYCoordinate:
    def __init__(self,y):
        self.x = x
        self.y = y
    def __hash__(self):
        return hash(tuple([self.x,self.y]))
    def __eq__(lhs,rhs):
        return hash(lhs) == hash(rhs)

xy1 = XYCoordinate(1,2)
xy2 = XYCoordinate(1,2)
print(hash(xy1))
print(hash(xy2))
print(xy1 == xy2)

输出为:

994727857
994727857
True

当您将某些内容用作字典键时,字典将使用哈希值。 dct[xy1] = "apple"dct[hash(xy1)] = "apple"

几乎

如果具有哈希值994727857的对象 更改 ,该怎么办?那将非常非常糟糕。

XYCoordinate类:     def init (自身,x,y):         self.x = x         self.y = y     def 哈希(自己):         返回hash(tuple([self.x,self.y]))     def eq (lhs,rhs):         返回hash(lhs)== hash(rhs)     def str (自己):         返回str(tuple([self.x,self.y]))     def repr (自己):         返回str(self)

d = dict()
xy1 = XYCoordinate(1,2)
xy2 = XYCoordinate(3,4)
d[xy1] = "apple"
d[xy2] = "banana"
print(d) 
# {(1,2): 'apple',(3,4): 'banana'}

# change `xy2` to be the "same" as xy1
xy2.x = xy1.x
xy2.y = xy1.y
print(xy2) # prints (1,2)
# d[(1,2)] = "orange"
d[xy2] = "orange"
print(d) 
# {(1,2): 'orange',(1,2): 'banana'}

看完以上内容,希望您问自己:“到底发生了什么?最后的字典{(1,2): 'banana'}怎么样?”

用作字典键的事物应该 从不 发生变化。

d[key] = 5

# key does not change
# key does not change
# [... a long time later]
# key does not change
# key does not change

d[key] = 99

由于尝试将字典(token)用作另一本字典的键而出错。

key_ab = {1:"apple"      2:"banana"}
key_cd = {1:"cantaloupe",2:"date" }

d = dict()
d[key_ab] = 4
d[key_cd] = 99

# key not supposed to change!
key_cd = {1:"apple",2:"banana" }

d[key_cd] = 104

无论用作字典键,请确保它们为 恒定 。数字4永远不变。您可以通过在门上写上“ {x”来更改酒店房间中的号码,但不能更改号码4。

同样,您可以更改哪个字符串留在哪个酒店房间,但是在python中,字符串“ apple”将永远是“ apple”。

您可以将整数,字符串,整数元组,字符串元组,frozensets和其他一些内容用于字典 应该可以更改,但不能更改 。您也可以使用定义了__hash__方法的任何东西,但是只有当您可以超级特殊地确定对象在调用hash之后永远不会改变时,才能这样做。第一次。

本文链接:https://www.f2er.com/3159796.html

大家都在问