键入dict.keys(),但dict.get(key)返回None

时间:2015-06-02 15:11:44

标签: python numpy dictionary

我有一本字典词典,dict[key1][key2]应该返回一个数字。 如果我执行key2 in dict[key1],则返回True,但dict[key1].get(key2)会返回None

我想这里有一些非常基本的东西,但是我被困了。

由于key1是string,而key2是numpy.datetime64

编辑:

key type: <type 'numpy.datetime64'>
key: 2014-08-11T02:00:00.000000+0200
Dict: {numpy.datetime64('2014-08-11T02:00:00.000000000+0200'): 1}
key in dict.keys() True
dict.items(): [(numpy.datetime64('2014-08-11T02:00:00.000000000+0200'), 1)]
dict.get(key): None

编辑2:

替换为编辑3

编辑3(替换编辑2):

代码:

vessel = df['Vessel'].iloc[0]
print "vessel:",vessel
ati = np.datetime64(df['ATI'].iloc[0])
print "ati type:",type(ati),"value:",ati
print "Self.sailing[vessel]:",self.sailing[vessel]
print "key in dict.keys():",ati in self.sailing[vessel].keys()
sailing = self.sailing[vessel].get(ati)
print "sailing:", sailing
print "dict[key]:",self.sailing[vessel][ati]

输出:

vessel: VESSEL2
ati type: <type 'numpy.datetime64'> value: 2014-07-21T02:00:00.000000+0200
Self.sailing[vessel]: {numpy.datetime64('2014-07-21T02:00:00.000000000+0200'): 1}
key in dict.keys(): True
sailing: None
dict[key]:
Traceback (most recent call last):
  File "C:/dev/python/bmw_vpc/src/vpc_data_extractor.py", line 9, in <module>
    data.create_master_file()
  File "C:\dev\python\bmw_vpc\src\process.py", line 112, in create_master_file
    print "dict[key]:",self.sailing[vessel][ati]
KeyError: numpy.datetime64('2014-07-21T02:00:00.000000+0200')

编辑4:

代码:

for key in self.sailing[vessel].keys():
    print "Vessel:",vessel,"ati:",ati,"ati == key:",ati == key
sailing = self.sailing[vessel].get(ati)
print "Vessel:",vessel,"sailing:", sailing

输出:

Vessel: VESSEL2 ati: 2014-07-21T02:00:00.000000+0200 ati == key: True
Vessel: VESSEL2 sailing: None

编辑5:

感谢@ jamylak的回答,我使用Timestamp而不是datetime64-object进行了解决方法。

4 个答案:

答案 0 :(得分:5)

您提供的信息中唯一的选项是key2中存在dict[key1],而key2的值为None

编辑:

它们是两个完全不同的对象,恰好看起来像完全相同的对象。

从您的代码中有:

numpy.datetime64('2014-07-21T02:00:00.000000+0200')

numpy.datetime64('2014-07-21T02:00:00.000000000+0200')
>>> (hash(numpy.datetime64('2014-07-21T02:00:00.000000000+0200'))
  == hash(numpy.datetime64('2014-07-21T02:00:00.000000+0200')))
False

原因是,当您检查in dict.keys()时,它会对由==构建的list中的每个元素执行相等检查(.keys())方法和

numpy.datetime64('2014-07-21T02:00:00.000000000+0200') == numpy.datetime64('2014-07-21T02:00:00.000000+0200')

如果您尝试投放key in dict,它将返回False,因为它不构建中间人list而是使用hash

它们是字典的不同对象,因为hash是字典使用的,这就是in dict.keys()不起作用的原因。

.get 找不到它,因为它返回None,您可以将默认None更改为其他内容以证明这一点。

至于他们比较相等且有不同hash的原因,我认为是某种错误。

答案 1 :(得分:1)

我已经尝试过以下代码段而没有任何问题。你能跟进并看看你是否仍然遇到同样的问题?

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> k = numpy.datetime64("2014-08-11T02:00:00.000000000+0200")
>>> print k
2014-08-11T08:00:00.000000000+0800
>>> dic = {"k":{k:1}}
>>> print dic
{'k': {numpy.datetime64('2014-08-11T08:00:00.000000000+0800'): 1}}
>>> dic.items()
[('k', {numpy.datetime64('2014-08-11T08:00:00.000000000+0800'): 1})]
>>> dic["k"].items()
[(numpy.datetime64('2014-08-11T08:00:00.000000000+0800'), 1)]
>>> dic["k"].get(k)
1
>>> 

答案 2 :(得分:0)

您可以尝试使用get两次:

dictionary.get('key1', {}).get('key2')

如果key1或key2不存在,则返回None。

答案 3 :(得分:0)

脚本中可能发生的有效示例:

>>> dict = {'key1': {'key2': None}}
>>> print('key2' in dict['key1'])
True
>>> print(dict['key1']['key2'])
None