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 key in python dictionary

How to change key in python dictionary:
for example:

data={'998905653388.0':('1254', '1255', 'Hello world'), =>
      '998905653388':('1254', '1255', 'Hello world')}

I tried like this:

for key in data.keys():
    new_key=key.split('.')
    data[key] = data[new_key[0]]
    data.pop(key, None)

But it throws an error:

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

TypeError: unhashable type: ‘list’

Or you can suggest other options.
Thank you.

>Solution :

You could iterate trought the list of your keys so it create a copy of them and once you modify keys inside your dict, it won’t conflict.

For each iteration you create a new key:val in your dict and pop out the old key

for key in list(data.keys()): data[key.split('.')[0]] = data.pop(key)
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