Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace dictionary keys (strings) in Python

After CSV import, I have following dictionary with keys in different language:

dic = {'voornaam': 'John', 'Achternaam': 'Davis', 'telephone': '123456', 'Mobielnummer': '234567'}

Now I want to change keys to English and (also to all lowercase). Which should be:

dic = {'first_name':  'John', 'last_name': 'Davis', 'phone': '123456', 'mobile': '234567'}

How can I achieve this?

like image 945
chhantyal Avatar asked Jul 29 '13 20:07

chhantyal


People also ask

Can we replace Key in dictionary Python?

Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.

Can I swap keys and values in dictionary Python?

You can swap keys and values in a dictionary with dictionary comprehensions and the items() method.

How do you overwrite a dictionary value in Python?

The Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.


1 Answers

you have dictionary type, it fits perfectly

>>> dic = {'voornaam': 'John', 'Achternaam': 'Davis', 'telephone': '123456', 'Mobielnummer': '234567'}
>>> tr = {'voornaam':'first_name', 'Achternaam':'last_name', 'telephone':'phone', 'Mobielnummer':'mobile'}
>>> dic = {tr[k]: v for k, v in dic.items()}
{'mobile': '234567', 'phone': '123456', 'first_name': 'John', 'last_name': 'Davis'}
like image 120
Roman Pekar Avatar answered Sep 22 '22 15:09

Roman Pekar