-1

I have a dictionary as follows:

d = {'a': ['b'], 'c': ['d']}

I want to change the positions of the dictionary so that it looks like the following:

d_new = {'b': 'a', 'd': 'c'}

I have tried the following, but due to the second term being a list in my original dictionary (d), I am unable to complete this.

d = {'a': ['b'], 'c': ['d']}

for k in list(d.keys()):

    d[d.pop(k)] = k

    print(d)
martineau
  • 112,593
  • 23
  • 157
  • 280
pr_kr1993
  • 3
  • 1

2 Answers2

2

You can use iterable unpacking in a dict comprehension like so:

{v: k for k, (v,) in d.items()}

>>> d = {'a': ['b'], 'c': ['d']}
>>> {v: k for k, (v,) in d.items()}
{'b': 'a', 'd': 'c'}

This assumes all values are a list of one element and you only want the first element in the lists.

Otherwise you can use this more appropriate code:

{v[0] if isinstance(v, list) else v: k for k, v in d.items()}
Jab
  • 25,138
  • 21
  • 72
  • 111
0

A variation on a theme using list unpacking:

d = {'a': ['b'], 'c': ['d']}

d = {v: k for k, [v] in d.items()}

print(d)

In case the values (lists) happen to contain more than one element and you're only interested in the first element then:

d = {v:k for k, [v,*_] in d.items()}

Of course, this could also be used even if there's only one element per list

Albert Winestein
  • 7,031
  • 2
  • 4
  • 14