python - Rename a dictionary key -
is there way rename dictionary key, without reassigning value new name , removing old name key; , without iterating through dict key/value?
in case of ordereddict, same, while keeping key's position.
for regular dict, can use:
mydict[new_key] = mydict.pop(old_key) for ordereddict, think must build entirely new 1 using comprehension.
>>> ordereddict(zip('123', 'abc')) ordereddict([('1', 'a'), ('2', 'b'), ('3', 'c')]) >>> oldkey, newkey = '2', 'potato' >>> ordereddict((newkey if k == oldkey else k, v) k, v in _.viewitems()) ordereddict([('1', 'a'), ('potato', 'b'), ('3', 'c')]) modifying key itself, question seems asking, impractical because dict keys immutable objects such numbers, strings or tuples. instead of trying modify key, reassigning value new key , removing old key how can achieve "rename" in python.
Comments
Post a Comment