6

Given the following list of dictionaries:

[
     {'Label': 'Acura', 'Value': '1'}, 
     {'Label': 'Agrale', 'Value': '2'}
]

How can I replace the word 'Label' with 'Make' and 'Value' with 'Code'?

I´m new to python and have tried many different approaches with no success.

Braiam
  • 1
  • 11
  • 47
  • 78
Hugo
  • 135
  • 1
  • 1
  • 7
  • 2
    Hi Hugo, could you please add the code of your "different approaches" at least one approach. It will make your question more clearer, please also what you expect as output. – Dani Mesejo Feb 11 '19 at 19:38

3 Answers3

16

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')
Jan
  • 42,290
  • 8
  • 54
  • 79
4

The simplest way is to add a new key with the old value, and then delete the old key:

mydict['Make'] = mydict['Label']
del mydict['Label']
John Gordon
  • 29,573
  • 7
  • 33
  • 58
3

Using pandas

import pandas as pd
df=pd.DataFrame([{'Label': 'Acura', 'Value': '1'}, {'Label': 'Agrale', 'Value': '2'}])
df=df.rename(index=str, columns={"Label": "Make", "Value": "Code"})
df.to_dict('records')
mad_
  • 8,121
  • 2
  • 25
  • 40