What is a pythonic way to remap each dictionary key in a list of identically-keyed dictionaries to different key names? E.g.,
[{'type_id': 6, 'type_name': 'Type 1'}, {'type_id': 12, 'type_name': 'Type 2'}]
must transform into
[{'type': 6, 'name': 'Type 1'}, {'type': 12, 'name': 'Type 2'}]
(I need to do the transformation in order to match an output specification for an API I'm working on.)
dict has no method to change the key, so add a new item with the new key and the original value, and then remove the old item.
Method #1: Using loop + items() This brute force way in which we can perform this task. In this, we loop through all the pairs and extract list value elements using items() and render them in a new list.
Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.
We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .
Python >= 2.7 (using a dict comprehension):
transform = {"type_id": "type", "type_name": "name"}
new_list = [{transform[k]: v for k, v in d.items()} for d in old_list]
Python >= 2.4 (using the dict constructor):
transform = {"type_id": "type", "type_name": "name"}
new_list = [dict((transform[k], v) for k, v in d.items()) for d in old_list]
How about inplace modifications?
>>> transform = {"type_id": "type", "type_name": "name"}
>>> for D in L:
for k,k_new in transform.items():
D[k_new] = D.pop(k)
>>> L
[{'type': 6, 'name': 'Type 1'}, {'type': 12, 'name': 'Type 2'}]
Or even better:
>>> for D in L:
for k,k_new in transform.items():
value = D.pop(k,None)
if value is not None:
D[k_new] = value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With