Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value?
In case of OrderedDict, do the same, while keeping that key's position.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
For a regular dict, you can use:
For an OrderedDict, I think you must build an entirely new one using a comprehension.
Modifying the key itself, as this question seems to be asking, is impractical because dict keys are usually immutable objects such as numbers, strings or tuples. Instead of trying to modify the key, reassigning the value to a new key and removing the old key is how you can achieve the "rename" in python.
best method in 1 line:
Using a check for
newkey!=oldkey
, this way you can do:You can use this
OrderedDict recipe
written by Raymond Hettinger and modify it to add arename
method, but this is going to be a O(N) in complexity:Example:
output:
Other answers are pretty good.But in python3.6, regular dict also has order. So it's hard to keep key's position in normal case.
A few people before me mentioned the
.pop
trick to delete and create a key in a one-liner.I personally find the more explicit implementation more readable:
The code above returns
{'a': 1, 'c': 2}