Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remapping key names in a list of dictionaries

Tags:

python

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.)

like image 887
B Robster Avatar asked Oct 31 '12 05:10

B Robster


People also ask

How do I change the dictionary key in a list?

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.

Can you convert a key value dictionary to list of lists?

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.

How list can be used as keys in dictionaries?

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.

Can you make a list a dictionary key?

We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .


2 Answers

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]
like image 183
Zero Piraeus Avatar answered Sep 24 '22 06:09

Zero Piraeus


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
like image 32
ovgolovin Avatar answered Sep 22 '22 06:09

ovgolovin