python 通过索引获取字典

发布于 2024-12-01 18:24:02 字数 586 浏览 1 评论 0原文

我有一个继承自字典的子类。在 __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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

掀纱窥君容 2024-12-08 18:24:02

不确定这是否是您正在寻找的...

class M(dict):

    def __getitem__(self, key):
        try:
            temp = int(key)
            return "I am a number"
        except ValueError:
            return self.get(key, None)

item = M({'one':'1', 'two':'2', '3':'three'})

print item['one']
print item[3]
print item[0]

正如 @bpgergo 所提到的,您还可以使用 super

所以返回看起来像这样:

    except ValueError:
        return super(M, self).__getitem__(key)

这里最大的区别是我的方法会(可能很糟糕)抑制因为您尝试访问不存在的密钥而引发的任何 KeyError 。

Not sure if this is what you are looking for...

class M(dict):

    def __getitem__(self, key):
        try:
            temp = int(key)
            return "I am a number"
        except ValueError:
            return self.get(key, None)

item = M({'one':'1', 'two':'2', '3':'three'})

print item['one']
print item[3]
print item[0]

As mentioned by @bpgergo, you can also use super.

So the return would look like this:

    except ValueError:
        return super(M, self).__getitem__(key)

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.

陌伤ぢ 2024-12-08 18:24:02
# continue the same way as it would have done

这里使用 super() 函数。 (这不是玩笑)
http://docs.python.org/library/functions.html#super

# continue the same way as it would have done

Here use the super() function. (this is not a joke)
http://docs.python.org/library/functions.html#super

空心↖ 2024-12-08 18:24:02

为此,在键不是数字的情况下,您需要调用父类的 __getitem__ 方法。这是通过 super() 函数完成的。请参阅下面的示例:

class cls(dict):
     def __getitem__(self, key):
         if isinstance(numbers.Number):
             print "I am a number"
         else:
             return super(cls, self).__getitem__(key)

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:

class cls(dict):
     def __getitem__(self, key):
         if isinstance(numbers.Number):
             print "I am a number"
         else:
             return super(cls, self).__getitem__(key)
芸娘子的小脾气 2024-12-08 18:24:02

您需要按字典的键列表进行索引。
示例:

x = dict({"name": "Tom", "surname": "Baker", "age": "55"})
print x[x.keys()[0]]
'55'

编辑:正如我怀疑的那样,不能保证订单。

“键和值以非随机的任意顺序列出,
因 Python 实现而异,并且取决于字典的
插入和删除的历史记录。如果 items()、keys()、values()、
调用 iteritems()、iterkeys() 和 itervalues() 时不需要
对字典进行干预修改,列表将直接
对应。这允许使用创建(值,键)对
zip():“pairs = zip(a.values(), a.keys())”。相同关系
适用于 iterkeys() 和 itervalues() 方法:“pairs =
zip(a.itervalues(), a.iterkeys())" 为对提供相同的值。
创建相同列表的另一种方法是“pairs = [(v, k) for (k, v) in
a.iteritems()]“。”

来源: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:

x = dict({"name": "Tom", "surname": "Baker", "age": "55"})
print x[x.keys()[0]]
'55'

Edit: As I suspected, the order is not guaranteed.

"Keys and values are listed in an arbitrary order which is non-random,
varies across Python implementations, and depends on the dictionary's
history of insertions and deletions. If items(), keys(), values(),
iteritems(), iterkeys(), and itervalues() are called with no
intervening modifications to the dictionary, the lists will directly
correspond. This allows the creation of (value, key) pairs using
zip(): "pairs = zip(a.values(), a.keys())". The same relationship
holds for the iterkeys() and itervalues() methods: "pairs =
zip(a.itervalues(), a.iterkeys())" provides the same value for pairs.
Another way to create the same list is "pairs = [(v, k) for (k, v) in
a.iteritems()]"."

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文