Change the name of a key in dictionary
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping
--
Chapters
00:00 Question
00:17 Accepted answer (Score 1066)
00:54 Answer 2 (Score 94)
01:15 Answer 3 (Score 46)
01:27 Answer 4 (Score 37)
02:11 Thank you
--
Full question
https://stackoverflow.com/questions/4406...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping
--
Chapters
00:00 Question
00:17 Accepted answer (Score 1066)
00:54 Answer 2 (Score 94)
01:15 Answer 3 (Score 46)
01:27 Answer 4 (Score 37)
02:11 Thank you
--
Full question
https://stackoverflow.com/questions/4406...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary
#avk47
ACCEPTED ANSWER
Score 1155
Easily done in 2 steps:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
Or in 1 step:
dictionary[new_key] = dictionary.pop(old_key)
which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[old_key].
>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1
ANSWER 2
Score 109
if you want to change all the keys:
d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}
In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}
if you want to change single key: You can go with any of the above suggestion.
ANSWER 3
Score 51
pop'n'fresh
>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>>
ANSWER 4
Score 42
In python 2.7 and higher, you can use dictionary comprehension: This is an example I encountered while reading a CSV using a DictReader. The user had suffixed all the column names with ':'
ori_dict = {'key1:' : 1, 'key2:' : 2, 'key3:' : 3}
to get rid of the trailing ':' in the keys:
corrected_dict = { k.replace(':', ''): v for k, v in ori_dict.items() }