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

How to change all the keys of a dictionary?

I have a dictionary like this {'lastname':'John', 'fistname':'Doe', 'id':'xxxxx'}
and I would like to add a prefix to all key values. The outcome should look like
{'contact_lastname':'John', 'contact_fistname':'Doe', 'contact_id':'xxxxx'}

I tried to achieve this by a lambda function, but did not work.

original = {'lastname':'John', 'fistname':'Doe', 'id':'xxxxx'}
modified = {(lambda k: 'contact_'+k) :v for k,v in original}

But it gives me an error. Any suggestions?

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

>Solution :

If you want to correct your code, you can iterate over keys and create tuple(k, v) and pass it to dict.

modified = dict(('contact_'+k, original[k]) for k in original)

Or you can use dict comprehension & f-string.

original= {'lastname':'John', 'fistname':'Doe', 'id':'xxxxx'}

modified = {f'contact_{k}' : v for k,v in original.items()}

print(modified)

{'contact_lastname': 'John', 'contact_fistname': 'Doe', 'contact_id': 'xxxxx'}
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