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)
Does anyone have any suggestions on how I can manage this? Any help will be highly appreciated.
CodePudding user response:
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()}
CodePudding user response:
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