作为dict键插入后,某些对象不会显示在键列表中

时间:2017-07-12 11:02:59

标签: python object dictionary hash

问题描述

我想将一个对象用作字典中的键。我想用来比较密钥的字典属性是:DDATE, WEEK_PERIOD, DPERIOD, RPERIOD, ALLIANCE, DTIME, RTIME。我想要排除属性DCXR, RCXR, DCNX, RCNX

算法的输出应为:

  

AC,DL,SN,AF,LH

问题是输出它只产生:

  

AC AF

其他值完全丢失。但是,当我将DCXR, RCXR, DCNX, RCNX添加到哈希 eq 时,我会得到正确的输出。但我不想要那样!当我在字典中插入键时,我不想使用它们。

我不明白为什么它会排除输出中的其他值。据我所知,当我将对象用作字典中的Key时,我不必使用所有属性。

以下源代码会产生错误。

源代码

#!/usr/bin/env python
import os
import sys
import argparse

from collections import defaultdict

from functools import partial

class Key(object):
    def __init__(self, DDATE, WEEK_PERIOD, DPERIOD, RPERIOD, ALLIANCE, DTIME, RTIME, DCXR, RCXR, DCNX, RCNX):
            self.DDATE       = DDATE
            self.WEEK_PERIOD = WEEK_PERIOD
            self.DPERIOD     = DPERIOD
            self.RPERIOD     = RPERIOD
            self.ALLIANCE    = ALLIANCE
            self.DTIME = DTIME
            self.RTIME = RTIME
            self.DCXR = DCXR
            self.RCXR = RCXR
            self.DCNX = DCNX
            self.RCNX = RCNX

    def __hash__(self):
        return hash((self.DDATE, self.WEEK_PERIOD, self.DPERIOD, self.RPERIOD, self.ALLIANCE,
                     self.DTIME, self.RTIME))

    def __eq__(self, other):
        return (self.DDATE, self.WEEK_PERIOD, self.DPERIOD, self.RPERIOD, self.ALLIANCE, 
        self.DTIME, self.RTIME) == (other.DDATE, other.WEEK_PERIOD, other.DPERIOD, other.RPERIOD, other.ALLIANCE, other.DTIME, other.RTIME)

    def __ne__(self, other):
        return not(self == other)


if __name__ == "__main__":

    dict = defaultdict(partial(defaultdict, list)) 

    key = Key("01/15/17","2","1","2","0","13:50","18:25","AF","AF","CDG","YUL")
    dict[key][28].append(10.0)

    key = Key("01/15/17","2","1","2","0","13:05","20:10","AC","AC","CDG","YUL")
    dict[key][28].append(20.0)

    key = Key("01/15/17","2","1","2","0","13:50","18:25","DL","DL","CDG","YUL")
    dict[key][28].append(30.0)

    key = Key("01/15/17","2","1","2","0","13:05","20:10","SN","SN","CDG","YUL")
    dict[key][28].append(40.0)

    key = Key("01/15/17","2","1","2","0","13:05","20:10","LH","LH","CDG","YUL")
    dict[key][28].append(50.0)

    for key in dict.keys():
        print key.DCXR

1 个答案:

答案 0 :(得分:1)

这些对象不会消失,它们永远不会作为键插入dict。您说您不希望在哈希计算中包含DCXR, RCXR, DCNX, RCNX。没关系。但是应该将它们包含在__eq__支票中。否则,仅在这些属性上不同的对象被视为相等。这与您的示例完全相同:

  • 第1和第3只在这些属性上有所不同。
  • 第2,第4和第5也仅在这些属性上有所不同。

所以会发生第1和第2个对象作为键插入,对于每个后续dict[key],旧值只是被覆盖,因为键比较相等。

旁注:您不应将dict用作变量名称,因为它会影响内置类型dict