简体   繁体   English

忽略关键字典python的一部分

[英]Ignoring part of a key dictionary python

I want to have a dictionary in which the keys are tuples such as (1, 0).我想要一个字典,其中的键是元组,例如 (1, 0)。 However, I want all keys of the form (n, 0) to identify with a similar output, and it'd be nice if I didn't have to have all the tuples from (1, 0) to (n, 0) as keys in my dictionary.但是,我希望 (n, 0) 形式的所有键都标识为类似的输出,如果我不必拥有从 (1, 0) 到 (n, 0) 的所有元组,那就太好了作为我字典中的键。 Is there a simple way I can do this?有没有一种简单的方法可以做到这一点?

dictionary = {(n, 1): [n, 3], (n, 2): [5, n], (n, 0): [0, n]}

If you want to make a dict with a special rule for handling keys that aren't actually stored in the dict hash table, you want to create a subclass of dict that implements __missing__ :如果要使用特殊规则来制作 dict 来处理实际上未存储在 dict 哈希表中的键,则需要创建一个实现__missing__dict子类:

Called by dict.__getitem__() to implement self[key] for dict subclasses when key is not in the dictionary.当 key 不在字典中时,由dict.__getitem__()调用以实现dict子类的self[key]

Like this:像这样:

class SpecialDict(dict):
    def __missing__(self, key):
        if isinstance(key, tuple) and len(key) == 2 and key[1] == 0:
            return [0, key]
        raise KeyError(key)

I don't really understand how your example is supposed to work, so here's a different example to demonstrate it:我不太明白你的例子应该如何工作,所以这里有一个不同的例子来证明它:

>>> d = SpecialDict({(1, 1): [2, 3], (1, 2): [5, 4]})
>>> d[1, 1]
[2, 3]
>>> d[2, 2]
KeyError: (2, 2)
>>> d[20, 0]
[0, 20]

If you store a value for a (n, 0) key, it won't call __missing__ for that key, allowing you to override a single (n, 0) while leaving the rest with their special rule:如果您为(n, 0)键存储一个值,它不会为该键调用__missing__ ,从而允许您覆盖单个(n, 0)同时保留其余键的特殊规则:

>>> d[42, 0] = [23, 23]
>>> d[42, 0]
[23, 23]
>>> d[23, 0]
[0, 23]

Just copy the value (1,0) to (n,0) and then delete the element (1,0) from dict.只需将值 (1,0) 复制到 (n,0),然后从 dict 中删除元素 (1,0)。 Like these:像这些:

dictionary[n,0] = dictionary[1,0]
del dictionary[1,0]

and so on, But for identifying for similar output you have to make the value into tuple by using set() and then take the difference with the key.等等,但是为了识别类似的输出,你必须使用 set() 将值变成元组,然后用键取差异。 Like these:像这些:

 for key in dictionary:
    if set(key) - set(dictionary[key]) is set():
       print("Similar key value pair")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM