Change the name of a key in dictionary
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
Rename dict keys in a list of dicts recursively
A recursive function should work, changing the sub-dicts if they contain column
and otherwise recursing deeper for other operations.
def change(collection):
if isinstance(collection, list):
return [change(d) for d in collection]
if isinstance(collection, dict):
if "column" in collection:
return {
"field": collection["column"]["name"],
"value": collection["value"],
"op": collection["operator"]
}
else:
return {op: change(val) for op, val in collection.items()}
res = change(filters)
Result:
[{'or': [{'and': [{'field': 'field_name', 'op': '==', 'value': 'field_value'},
{'field': 'field_2_name', 'op': '!=', 'value': 'field_2_value'}]},
{'not': [{'field': 'field_3_name', 'op': '==', 'value': 'field_3_value'}]}]}]
How to rename dictionary keys to follow sequential order?
A simple dictionary comprehension:
d2 = {i: v for i, v in enumerate(d2.values())}
As said by Ma0 in comments, a list would be more adequate. You can retrieve the list as d1.values()
.
How do I rename a key while preserving order in dictionaries (Python 3.7+)?
This solution modifies the dictionary d
in-place. If performance is not a concern, you could do the following:
d = {"a": 1, "b": 2, "c": 3, "d": 4}
replacement = {"b": "B"}
for k, v in list(d.items()):
d[replacement.get(k, k)] = d.pop(k)
print(d)
Output:
{'a': 1, 'B': 2, 'c': 3, 'd': 4}
Notice that the above solution will work for any numbers of keys to be replaced. Also note that you need to iterate over a copy of d.items()
(using list(d.items())
), as you shouldn't iterate over a dictionary while modifying its keys.
How to change dictionary keys in a list of dictionaries?
Use .pop
:
lst = [{'Label': 'Acura', 'Value': '1'}, {'Label': 'Agrale', 'Value': '2'}]
for d in lst:
d['Make'] = d.pop('Label')
d['Code'] = d.pop('Value')
print(lst)
This yields
[{'Make': 'Acura', 'Code': '1'}, {'Make': 'Agrale', 'Code': '2'}]
If the key happens to not exist. you could define a default key as well:
d['new_key'] = d.pop('missing_key', 'default_value')
Rename the keys in a dictionary efficiently
You can use a dictionary comprehension:
d = {0: -1.0, 21: 2.23, 7: 7.1, 46: -12.0}
d = {f"p{k}":v for k,v in d.items()}
print(d)
Output:
{'p0': -1.0, 'p21': 2.23, 'p7': 7.1, 'p46': -12.0}
Note that this will work too:
d = {f"p{k}":d[k] for k in d}
Renaming the keys of a dictionary
dict
keys are immutable. That means that they cannot be changed. You can read more from the docs
dictionaries are indexed by keys, which can be any immutable type
Here is a workaround using dict.pop
>>> d = {1:'a',2:'b'}
>>> d[3] = d.pop(1)
>>> d
{2: 'b', 3: 'a'}
python: how to change the name of a key in a dictionary
You do need to remove and re-add, but you can do it one go with pop
:
d['hi'] = d.pop('hii')
Related Topics
How to Get the Number of Elements in a List in Python
Fixed Digits After Decimal with F-Strings
What's the Scope of a Variable Initialized in an If Statement
Best Way to Find the Intersection of Multiple Sets
Change One Value Based on Another Value in Pandas
Strings in a Dataframe, But Dtype Is Object
Python Garbage Collector Documentation
How to Convert a String of Bytes into an Int
Checking Whether a String Starts with Xxxx
Differencebetween a Function, an Unbound Method and a Bound Method
How to Escape Os.System() Calls
Store Different Datatypes in One Numpy Array