partial match dictionary key(of tuples) in python

后端 未结 4 1349
长发绾君心
长发绾君心 2020-12-09 13:00

I have a dictionary that maps 3tuple to 3tuple where key-tuples have some element in common

dict= { (a,b,c):(1,2,3),
        (a,b,d):tuple1,
        (a,e,b):         


        
4条回答
  •  无人及你
    2020-12-09 13:07

    You could reconstruct your dictionary into a triply nested dict.

    dict= { ("foo", 4 , "q"): 9,
            ("foo", 4 , "r"): 8,
            ("foo", 8 , "s"): 7,
            ("bar", 15, "t"): 6,
            ("bar", 16, "u"): 5,
            ("baz", 23, "v"): 4
          }
    
    d = {}
    for (a,b,c), value in dict.iteritems():
        if a not in d:
            d[a] = {}
        if b not in d[a]:
            d[a][b] = {}
        d[a][b][c] = value
    

    Here, d is equivalent to:

    d = {
        "foo": {
            4:{
                "q": 9,
                "r": 8
            },
            8:{
                "s": 7
            }
        },
        "bar":{
            15:{
                "t": 6
            }
            16:{
                "u": 5
            }
        },
        "baz":{
            23{
                "v": 4
            }
        }
    }
    

    Now you can easily iterate through the possible third keys, given the first and second.

    #find all keys whose first two elements are "foo" and 4
    a = "foo"
    b = 4
    for c in d[a][b].iterkeys():
        print c
    

    Result:

    q
    r
    

    This only works for matching the third key. For instance, you wouldn't be able to find all second keys, given the third and the first.

提交回复
热议问题