-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
  • 119,623
  • 25
  • 170
  • 301
pr_kr1993
  • 185
  • 6

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
  • 26,853
  • 21
  • 75
  • 114
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

DarkKnight
  • 19,739
  • 3
  • 6
  • 22