How to swap the key and value in a python dictionary
There are cases that you may want to reverse the key and value pair in a python dictionary, so that you can do some operation by using the unique values in the original dictionary.
For instance, if you have the below dictionary:
contact = {"joe" : "contact@company.com", "john": "john@company.com"}
you can reverse it by:
contact = {val : key for key, val in contact.items()} print(contact)
You will see the below output:
{'contact@company.com': 'joe', 'john@company.com': 'john'}
But for the above dictionary, if multiple names sharing the same email address, then only one name will be retained. e.g. :
contact = {"joe" : "contact@company.com", "jane" : "contact@company.com", "john": "john@company.com"} contact = {val : key for key, val in contact.items()}
Output of the contact dictionary will be :
{'contact@company.com': 'jane', 'john@company.com': 'john'}
so how to keep all the keys that have the same value after reversing it ?
You will need to use a list or set to collect all the keys if the value is the same, e.g.:
email_contact = {} for key, val in contact.items(): email_contact.setdefault(val, []).append(key)
(please refer to this article about the setdefault method)
And you will see the below output for the new dictionary email_contact:
{'contact@company.com': ['joe', 'jane'], 'john@company.com': ['john']}
That’s exactly what we want ! Now we shall be able to say “hi” to both Joe and Jane when sending email to contact@company.com without missing any names.
As per always, welcome any comments or questions.
Originally published at https://www.codeforests.com on June 13, 2020.