字典与Python的反向映射 [英] reverse mapping of dictionary with Python

查看:107
本文介绍了字典与Python的反向映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

反词典查找 - Python

如果我有一个名为ref的字典如下

If I have a dictionary named ref as follows

ref = {}
ref["abc"] = "def"

我可以从abc获得def

I can get "def" from "abc"

def mapper(from):
    return ref[from]

但是,如何从def到abc?

But, how can I get from "def" to "abc"?

def revmapper(to):
    ??????


推荐答案

如果经常这样做,构建一个反向字典:

If you do this often, you'll want to build a reverse dictionary:

>>> rev_ref = dict((v,k) for k,v in ref.iteritems())
>>> rev_ref
{'def': 'abc'}

>>> def revmapper(to):
...    return rev_ref[to]

如果很少,而且你不在乎它是否没有效率,请执行以下操作:

If it's rare, and you don't care if it's inefficient, do this:

>>> def revmapper(to):
...    for k,v in ref.iteritems():
...      if v == to: return k

这篇关于字典与Python的反向映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆