5

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
  • 50
  • 74
Hugo
  • 125
  • 1
  • 1
  • 6
  • 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

11

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
  • 40,932
  • 8
  • 45
  • 77
3

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
  • 23,292
  • 7
  • 28
  • 49
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_
  • 7,844
  • 2
  • 22
  • 37