Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping keys and values with nested value items

I have a list of standard names

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

and a dictionary of aliases (in this case nicknames)

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

I want to make a new dictionary that I can put any of the alias names in as a key and it will return the standard name AKA swap the key and value

My only guess so far was this

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

is there a neater or more readable way to do this (id prefer not having the temporary dictionary t).

like image 461
Paul Seeb Avatar asked Oct 23 '25 16:10

Paul Seeb


2 Answers

I think this would be more readable:

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

If you prefer some form of generator expression you can use these:

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)
like image 84
Sven Marnach Avatar answered Oct 26 '25 05:10

Sven Marnach


>>> 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']
>>> 

List comprehensions are awesome.

like image 22
TyrantWave Avatar answered Oct 26 '25 06:10

TyrantWave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!