Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

partial match dictionary key(of tuples) in python

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):tuple,
        .
        (f,g,h):tuple3,
        .
        .
        .
        tuple:tuple
      }

now how can I find the values that match to (a,b,anyX) in a dictionary ie (1:2:3) and tuple1

this is computer generated and very large thus, it takes effort to determine anyX.

so, any good ways I can do this?

edit:partial matching of (f,g,*),(f, *,g) to tuple3 will also be helpful but not necessary.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Lets say if you're passing None for the missing keys then you can use all and zip:

>>> from itertools import permutations
>>> import random
#create a sample dict
>>> dic = {k:random.randint(1, 1000) for k in permutations('abcde', 3)}
def partial_match(key, d):
    for k, v in d.iteritems():
        if all(k1 == k2 or k2 is None  for k1, k2 in zip(k, key)):
            yield v
...         
>>> list(partial_match(('a', 'b', None), dic))
[541, 470, 734]
>>> list(partial_match(('a', None, 'b'), dic))
[460, 966, 45]
#Answer check
>>> [dic[('a', 'b', x)] for x in 'cde']
[541, 734, 470]
>>> [dic[('a', x, 'b')] for x in 'cde']
[966, 460, 45]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...