2d dictionary with many keys that will return the same value

前端 未结 2 1323
臣服心动
臣服心动 2021-01-03 10:17

I want to make a 2d dictionary with multiple keys per value. I do not want to make a tuple a key. But rather make many keys that will return the same value.

I know ho

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 10:38

    Does this help at all?

    class MultiDict(dict):
        # define __setitem__ to set multiple keys if the key is iterable
        def __setitem__(self, key, value):
            try:
                # attempt to iterate though items in the key
                for val in key:
                    dict.__setitem__(self, val, value)
            except:
                # not iterable (or some other error, but just a demo)
                # just set that key
                dict.__setitem__(self, key, value)
    
    
    
    x = MultiDict()
    
    x["a"]=10
    x["b","c"] = 20
    
    print x
    

    The output is

    {'a': 10, 'c': 20, 'b': 20}
    

提交回复
热议问题