Reputation: 23
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.
Upvotes: 0
Views: 90
Reputation: 4965
A slightly different way with str.partition
method.
for key in list(data):
data[key.partition('.')[0]] = data.pop(key)
Upvotes: 0
Reputation: 3624
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)
Upvotes: 1
Reputation: 648
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)
Upvotes: 0