0

How to replace value with key in dictionary?

For example: a={1:'a',2:'b'} Now I want a new dictionary: a={'a':1,'b':2}

14th Oct 2021, 10:47 AM
Amirreza
Amirreza - avatar
5 Réponses
+ 3
a={y:x for x,y in a.items()}
14th Oct 2021, 11:23 AM
ubai
ubai - avatar
+ 2
Amirreza Hashemi What if there are duplicate values? In this case when you swap then new key will replace old key. For example: a = {1: 'a', 2 : 'b', 3 : 'b'} In this case result will be a = {a : 1, b : 3} So to avoid this above solutions are ok.
14th Oct 2021, 2:13 PM
A͢J
A͢J - avatar
14th Oct 2021, 11:16 AM
Amirreza
Amirreza - avatar
+ 1
ubai that's what I was expected... Thank you
14th Oct 2021, 11:27 AM
Amirreza
Amirreza - avatar