[英]Key in dict.keys(), but dict.get(key) returns None
I have a dictionary of dictionaries ie dict[key1][key2]
should return a number. 我有字典的字典,即
dict[key1][key2]
应该返回一个数字。 If I do key2 in dict[key1]
this returns True
, but dict[key1].get(key2)
returns None
. 如果我
key2 in dict[key1]
执行key2 in dict[key1]
返回True
,但是dict[key1].get(key2)
返回None
。
I guess there is something quite fundamental I'm missing here, but I'm stuck. 我猜这里有些根本的东西我不见了,但是我被卡住了。
As key1 is a string
, and key2 is a numpy.datetime64
. 由于key1是
string
,而key2是numpy.datetime64
。
edit: 编辑:
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
edit 2: 编辑2:
replaced by edit 3 替换为编辑3
Edit 3 (replacing edit 2): 编辑3(取代编辑2):
Code: 码:
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]
Output: 输出:
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')
edit 4: 编辑4:
code: 码:
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
output: 输出:
Vessel: VESSEL2 ati: 2014-07-21T02:00:00.000000+0200 ati == key: True
Vessel: VESSEL2 sailing: None
edit 5: 编辑5:
Thanks to @jamylak's answer I made a workaround using the Timestamp instead of the the datetime64-object. 感谢@jamylak的回答,我使用时间戳而不是datetime64对象进行了变通。
The only option from the information you have given is that key2
exists in dict[key1]
and key2
has a value of None
您提供的信息中的唯一选择是
key2
存在于dict[key1]
并且key2
的值为None
EDIT: 编辑:
They are 2 completely different objects that just happen to look like the exact same object. 它们是2个完全不同的对象,它们恰好看起来像是完全相同的对象。
From your code there is: 在您的代码中有:
numpy.datetime64('2014-07-21T02:00:00.000000+0200')
and 和
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
The reason this is, is because when you check in dict.keys()
it does an equality check ( ==
) on each element in a list
that is built by the .keys()
method and 这是因为,当您签
in dict.keys()
它将对由.keys()
方法构建的list
中的每个元素进行相等检查( ==
),并且
numpy.datetime64('2014-07-21T02:00:00.000000000+0200') == numpy.datetime64('2014-07-21T02:00:00.000000+0200')
If you try running key in dict
, it will return False
because that doesnt build the intermediary list
and instead uses hash
如果您尝试
key in dict
运行key in dict
,它将返回False
因为这不会建立中介list
,而是使用hash
They are different objects to the dictionary because the hash
is what the dictionary uses which is why in dict.keys()
does not work. 它们是与字典不同的对象,因为字典使用的是
hash
,这就是为什么in dict.keys()
不起作用的原因。
.get
also does not find it because it returns None
, you can change the default None
to something else to prove this. .get
也因为它返回没有找到它None
,你可以更改默认None
别的东西来证明这一点。
As for the reason why they compare equal and have a different hash
, I think some sort of bug. 至于为什么它们比较相等并且具有不同的
hash
,我认为是某种错误。
I have tried the following section of code with no issue. 我已经尝试了以下代码部分,没有任何问题。 Can you follow through and see if you still get the same issue?
您可以继续查看是否仍然遇到相同的问题吗?
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
>>>
You could try to use get twice: 您可以尝试使用get两次:
dictionary.get('key1', {}).get('key2')
This will return None if key1 or key2 does not exist. 如果key1或key2不存在,则将返回None。
A valid example of what probably happen in your script: 一个有效的示例,说明脚本中可能发生的情况:
>>> dict = {'key1': {'key2': None}}
>>> print('key2' in dict['key1'])
True
>>> print(dict['key1']['key2'])
None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.