B Robster
B Robster

Reputation: 42043

Remapping key names in a list of dictionaries

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

Upvotes: 6

Views: 1938

Answers (4)

schesis
schesis

Reputation: 59128

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]

Upvotes: 8

ovgolovin
ovgolovin

Reputation: 13410

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

Upvotes: 3

Joran Beasley
Joran Beasley

Reputation: 113978

just use a list comprehension

>>> d = [{'type_id': 6, 'type_name': 'Type 1'}, {'type_id': 12, 'type_name': 'Type 2'}]
>>> print [{'type':x['type_id'],'name':x['type_name']} for x in d]
[{'type': 6, 'name': 'Type 1'}, {'type': 12, 'name': 'Type 2'}]
>>>

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174624

The new-user-friendly, easy-to-read way:

>>> list2 = []
>>> for d in list1:
...     x = dict()
...     for k,v in d.iteritems():
...        x[k.split('_')[1]] = v
...     list2.append(x)
...
>>> list2
[{'name': 'Type 1', 'id': 6}, {'name': 'Type 2', 'id': 12}]

Upvotes: 1

Related Questions