使用嵌套值项交换键和值

时间:2012-01-11 16:39:28

标签: python dictionary nested

我有一个标准名称列表

standard = ["Richard","Robert","Nicolas"]

和别名字典(在这种情况下是昵称)

aliases = {standard[0]:["Richard","Rick","Dick","Rich"],
           standard[1]:["Robert","Roberto","Bob"],
           standard[2]:["Nicolas","Nick","Nic"]}

我想创建一个新的字典,我可以将任何别名作为键,它将返回标准名称AKA交换键和值

我到目前为止唯一的猜测就是这个

t = {}
aliases = [t.update(zip(v,[k]*len(v))) for k,v in aliases.items()]
aliases = t

是否有更简洁或更易读的方法(id不喜欢临时字典t)。

4 个答案:

答案 0 :(得分:5)

我认为这会更具可读性:

rev_aliases = {}
for name, nick_list in aliases.iteritems():
    for nick in nick_list:
        rev_aliases[nick] = name

如果你喜欢某种形式的生成器表达式,你可以使用它们:

Python> = 2.7:

rev_aliases = {nick: name 
               for name, nick_list in aliases.viewitems()
               for nick in nick_list}

Python< 2.7:

rev_aliases = dict((nick, name)
                   for name, nick_list in aliases.iteritems()
                   for nick in nick_list)

答案 1 :(得分:1)

>>> standard = ["Richard","Robert","Nicolas"] 
>>> aliases = {standard[0]:["Richard","Rick","Dick","Rich"], 
           standard[1]:["Robert","Roberto","Bob"] ,
           standard[2]:["Nicolas","Nick","Nic"] }
>>> def name(nickname):
        return [n for n in aliases if nickname in aliases[n]]

>>> name('Bob')
['Robert']
>>> 

列表理解非常棒。

答案 2 :(得分:1)

dict((nick, name) for name, nicks in aliases.iteritems() for nick in nicks)

答案 3 :(得分:0)

滥用itertools的有趣方式:

>>> from itertools import izip, repeat, chain
>>> dict(chain.from_iterable(
        izip(iter(b), repeat(a, len(b)))
        for a, b in aliases.iteritems()))
{'Nicolas': 'Nicolas',
 'Richard': 'Richard',
 'Nic': 'Nicolas',
 'Robert': 'Robert',
 'Dick': 'Richard',
 'Roberto': 'Robert',
 'Nick': 'Nicolas',
 'Rick': 'Richard',
 'Rich': 'Richard',
 'Bob': 'Robert'}