Reputation: 21
I have dictionary
d= {1:[2],2:[3],3:[4]}
i want to swap only a particular key with its values.
so if I want to swap the first key then the dictionary will be
d= {2:[1,3],3:[4]}
how I can achieve this?
I tried
d.iteritems()
but it swaps all the keys of the dictionary.
Thanks in advance. and this is not homework.
Upvotes: 2
Views: 56
Reputation: 82765
This is one approach dict.pop
and dict.setdefault
Ex:
d= {1:[2],2:[3],3:[4]}
key_to_swap = 1
for value in d.pop(key_to_swap):
d.setdefault(value, []).append(key_to_swap)
print(d)
Upvotes: 1