简体   繁体   中英

Ignoring part of a key dictionary python

I want to have a dictionary in which the keys are tuples such as (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. 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__ :

Called by dict.__getitem__() to implement self[key] for dict subclasses when key is not in the dictionary.

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:

>>> 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. 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. Like these:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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