Problem description
I want to used an object as a key in a dictionary. The attributes of the dictionary that I want to use to compare the keys are: DDATE, WEEK_PERIOD, DPERIOD, RPERIOD, ALLIANCE, DTIME, RTIME
. I want exclude the attributes DCXR, RCXR, DCNX, RCNX
.
The output of the algorithm should be:
AC, DL, SN, AF, LH
The problem is that as output it is only producing:
AC AF
The other values are totally lost. However When I add DCXR, RCXR, DCNX, RCNX
to the hash and eq I get the right output. But I don't want THAT!! I don't want to use them when I insert keys in the dictionary.
I don't understand why it is excluding the other values in the output. From what I know I don't have to use all the attributed when I use the object as a Key in a dictionary.
The following source code produces exactly the error.
Source code
#!/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