Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dict with key/value and key/value reversed

Having such list

example = ['ab', 'cd']

I need to get {'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}

With regular loop I could do this like:

result = {}
for i,j in example:
    result[i] = j
    result[j] = i

Question: How can I do the same on one line?

like image 524
micgeronimo Avatar asked Mar 08 '26 02:03

micgeronimo


1 Answers

Another possible solution:

dict(example + [s[::-1] for s in example])

[s[::-1] for s in example] creates a new list with all strings reversed. example + [s[::-1] for s in example] combines the lists together. Then the dict constructor builds a dictionary from the list of key-value pairs (the first character and the last character of each string):

In [5]: dict(example + [s[::-1] for s in example])
Out[5]: {'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}
like image 199
vaultah Avatar answered Mar 09 '26 14:03

vaultah