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?
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'}
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