python 通过索引获取字典
我有一个继承自字典的子类。在 __getitem__ 方法中,我想检查键是否是数字。如果它是数字,我想实现一些其他行为,如果不是,那么我想像平常一样继续。示例:
class M(dict):
...
def __getitem__(self, key):
if self.isNumber(key):
print "I am number"
else:
# continue the same way as it would have done
...
>>> x = M({"name": "Tom", "surname": "Baker", "age": "55"})
>>> print x["name"]
Tom
>>> x[0]
I am number
我该怎么做?
更新
我知道字典中的项目是散列的,因此它不会按顺序排列,我问的原因背后是别的东西。因为我确信您仍然会问为什么,这就是原因:字典是一个对象,我将通过索引检索与给定对象相关的对象。 (作为父母思考,孩子的事情)
I have subclass that inherits from a dict. On __getitem__
method I'd like to check whether the key is numeric or not. If it is numeric I'd like to implement some other behavior and if it not then I'd like continue as it would normally do. Example:
class M(dict):
...
def __getitem__(self, key):
if self.isNumber(key):
print "I am number"
else:
# continue the same way as it would have done
...
>>> x = M({"name": "Tom", "surname": "Baker", "age": "55"})
>>> print x["name"]
Tom
>>> x[0]
I am number
How can I do this?
UPDATE
I know that items in dict are hashed therefore it will not be in order, the reason behind what I ask is something else. And since I'm sure you'll still ask why, this is the reason: The dict is an object and I will retrieve the objects related to the given object by their index. (Think as parent, child stuff)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不确定这是否是您正在寻找的...
正如 @bpgergo 所提到的,您还可以使用
super
。所以返回看起来像这样:
这里最大的区别是我的方法会(可能很糟糕)抑制因为您尝试访问不存在的密钥而引发的任何 KeyError 。
Not sure if this is what you are looking for...
As mentioned by @bpgergo, you can also use
super
.So the return would look like this:
The big difference here is that my way would (perhaps poorly) suppress any KeyError that was raised because you tried to access a key that does not exist.
这里使用
super()
函数。 (这不是玩笑)http://docs.python.org/library/functions.html#super
Here use the
super()
function. (this is not a joke)http://docs.python.org/library/functions.html#super
为此,在键不是数字的情况下,您需要调用父类的
__getitem__
方法。这是通过 super() 函数完成的。请参阅下面的示例:For this you need to invoke the parent class's
__getitem__
method in the case of the key not being numeric. This is done with the super() function. See the example below:您需要按字典的键列表进行索引。
示例:
编辑:正如我怀疑的那样,不能保证订单。
来源:http://docs.python.org/release/2.5.2 /lib/typesmapping.html
考虑到这一点,我认为最好不要假设 SLA 来自字典(键的顺序不会改变)
You need to index by the list of the keys for the dictionary.
Example:
Edit: As I suspected, the order is not guaranteed.
Source: http://docs.python.org/release/2.5.2/lib/typesmapping.html
With this in mind, I think its better not assume that SLA from a dictionary (That the keys' order will not change)