reverse mapping of dictionary with Python
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Inverse dictionary lookup - Python
如果我有一本叫REF的字典
1 2 | ref = {} ref["abc"] ="def" |
我可以从"abc"得到"def"
1 2 | def mapper(from): return ref[from] |
但是,我怎样才能从"def"变成"abc"?
1 2 | def revmapper(to): ?????? |
如果经常这样做,您将希望构建一个反向字典:
1 2 3 4 5 6 | >>> rev_ref = dict((v,k) for k,v in ref.iteritems()) >>> rev_ref {'def': 'abc'} >>> def revmapper(to): ... return rev_ref[to] |
如果它很少见,而且你不在乎它是否低效,那么就这样做:
1 2 3 | >>> def revmapper(to): ... for k,v in ref.iteritems(): ... if v == to: return k |
你可以制作一本反向字典:
1 | revdict = dict((v,k) for k,v in ref.items()) |
然后查找所需内容:
1 | assert revdict["def"] =="abc" |
注意,如果两个键映射到相同的值,这将不起作用。
1 | dict(map( lambda a:[a[1],a[0]], d.iteritems() )) |