micgeronimo
micgeronimo

Reputation: 2149

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?

Upvotes: 3

Views: 113

Answers (5)

vaultah
vaultah

Reputation: 46583

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

Upvotes: 2

Tonechas
Tonechas

Reputation: 13743

A dict comprehension should do:

In [726]: {k: v for (k, v) in map(tuple, example + map(reversed, example))}  # Python 2
Out[726]: {'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}

In [727]: {s[0]: s[1] for s in (example + [x[::-1] for x in example])}  # Python 3
Out[727]: {'b': 'a', 'a': 'b', 'd': 'c', 'c': 'd'}

Upvotes: 0

khelili miliana
khelili miliana

Reputation: 3822

example = ['ab', 'cd']

res1={x[1]:x[0] for x in example}
res2={x[0]:x[1] for x in example}
res=res1.update(res2)
print res1

Upvotes: 0

janbrohl
janbrohl

Reputation: 2656

You can use ; to seperate logical lines

result=dict(example); result.update((k,v) for v,k in example)

But of course

result=dict(example+map(reversed,example)) # only in python 2.x

or

result=dict([(k,v) for k,v in example]+[(k,v) for v,k in example])

work, too.

Upvotes: 0

James Tobin
James Tobin

Reputation: 3110

list comprehension with dictionary updates

[result.update({x[0]:x[1],x[1]:x[0]}) for x in example]

Upvotes: 0

Related Questions