문제

I have an tcl dict containing keys and their values. Is there a way to do a "reverse lookup" eg looking for the value, and retrieving the key. I know that this does not sound like state of the art programming, but the dict already exists in my code and I would not like to recreate it the other way around just because of this one time I need it.

도움이 되었습니까?

해결책

You can use the dict filter command. Values can repeat, so you should expect more than one single key.

set d [dict create a b c d e b]
# note that the "b" value is repeated for keys "a" and "e"

dict filter $d value b
-> a b e b

So you can use something like this:

set lookupVal b
dict for {k v} [dict filter $d value $lookupVal] {
    lappend keys $k
}

puts $keys
-> a e

다른 팁

If your values are unique, the dirty-hack way to get the key for a particular value is this:

set theKey [dict get [lreverse $theDict] $theValue]

I wouldn't particularly recommend it as it's a type-buster, but it will do the right thing. (If you've got the same value several times, this will return the key for the first instance.)

Note that you still retain the original dictionary in $theDict if you do this. (Well, assuming you're satisfied with Tcl's detailed type semantics when behind-the-scenes type conversions are happening.)


If you're thinking about doing this more than very occasionally, consider keeping a reversed dictionary around alongside the original so that you can do the lookup rapidly. This applies even if you use the dict keys [dict filter …] solution; linear scans of anything large can definitely slay you otherwise.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top