For a regular dict, you can use:
mydict[k_new] = mydict.pop(k_old)
This will move the item to the end of the dict, unless k_new was already existing in which case it will overwrite the value in-place.
For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2 to 'two':
>>> d = {0:0, 1:1, 2:2, 3:3}
>>> {"two" if k == 2 else k:v for k,v in d.items()}
{0: 0, 1: 1, 'two': 2, 3: 3}
The same is true for an OrderedDict, where you can't use dict comprehension syntax, but you can use a generator expression:
OrderedDict((k_new if k == k_old else k, v) for k, v in od.items())
Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies they're immutable and can't be modified.
Answer from wim on Stack OverflowFor a regular dict, you can use:
mydict[k_new] = mydict.pop(k_old)
This will move the item to the end of the dict, unless k_new was already existing in which case it will overwrite the value in-place.
For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2 to 'two':
>>> d = {0:0, 1:1, 2:2, 3:3}
>>> {"two" if k == 2 else k:v for k,v in d.items()}
{0: 0, 1: 1, 'two': 2, 3: 3}
The same is true for an OrderedDict, where you can't use dict comprehension syntax, but you can use a generator expression:
OrderedDict((k_new if k == k_old else k, v) for k, v in od.items())
Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies they're immutable and can't be modified.
Using a check for newkey!=oldkey, this way you can do:
if newkey!=oldkey:
dictionary[newkey] = dictionary[oldkey]
del dictionary[oldkey]
How to change the name of a key in a dictionary, ideally without deleting it?
How to change a dicts value for one of the keys?
Renaming duplicate keys in a dictionary
How do I map the keys of a dictionary to the columns of a pandas dataframe?
Keep this paradigm in your head: dataframes are meant to be instantiated from a data source, they aren't meant to be created as a blank sheet and 'filled in' later on. So also in this case: don't build a dataframe upfront, instead create the dataframe using the dict as the basis for its data. From Create a Pandas DataFrame from List of Dicts:
cols = ['timestamp', 'name', 'adress', 'phone', 'website', 'rating', 'number_of_ratings', 'type'] df = pd.DataFrame(multidict, columns=cols)More on reddit.com
I have { key1 : value1 }, which I want to rename to { key2 : value1 }. Google has told me to just delete key1 and create a new key2, but value1 is a complicated, frequently-changing mess, and I don't really want to have to keep updating it.
Any ideas? Is there a method that I'm missing?