How to change key in python dictionary

Question:

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:

TypeError: unhashable type: ‘list’

Or you can suggest other options.
Thank you.

Asked By: bestmovie clips

||

Answers:

Lists cannot be dictionary keys.

str.split returns a list. I think you mean key.split('.')[0] – which will give a string.

for key in list(data.keys()):
    new_key = key.split('.')[0]
    data[new_key] = data[key]
    data.pop(key, None)
Answered By: The Thonnu

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)
Answered By: ArrowRise

A slightly different way with str.partition method.

for key in list(data):
    data[key.partition('.')[0]] = data.pop(key)
Answered By: cards
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.