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).
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)
>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With