Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python change all keys of a dictionary

How do I change all keys of a dictionary

code:

d1 = {'mango':10,
          'bananna':20,
          'grapes':30}
d1_new_keys = ['yellow mango','green banana','red grapes']
d1.keys() = d1_new_keys

present answer:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SyntaxError: can't assign to function call

expected answer:

d1 = {'yellow mango': 10, 'green bananna': 20, 'red grapes': 30}

>Solution :

What you’re doing is trying to set the function d1.keys() to a list thus the error. The best way to do this would be with dictionary comprehension:

d1 = {k: v for (k, v) in zip(d1_new_keys, d1.values()}

This would essentially create a new dictionary and set it equal to d1 where the keys come from the d1_new_keys list and the values come from the original d1

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading