chhantyal
chhantyal

Reputation: 12252

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?

Upvotes: 9

Views: 14377

Answers (3)

Sunil
Sunil

Reputation: 97

Above solution works great if there are NO nested dictionary objects in input dict.

Below is more generalized utility function that replaces existing keys with new set of keys recursively.

def update_dict_keys(obj, mapping_dict):
    if isinstance(obj, dict):
        return {mapping_dict[k]: update_dict_keys(v, mapping_dict) for k, v in obj.iteritems()}
else:
    return obj

Test:

dic = {'voornaam': 'John', 'Achternaam': 'Davis', 
'telephone':'123456', 'Mobielnummer': '234567',
"a": {'Achternaam':'Davis'}}
tr = {'voornaam': 'first_name', 'Achternaam': 'last_name', 
'telephone':'phone', 'Mobielnummer': 'mobile', "a": "test"}

Output:

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

Upvotes: 1

roman
roman

Reputation: 117345

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'}

Upvotes: 24

Maciej Gol
Maciej Gol

Reputation: 15854

name_mapping = {
    'voornaam': 'first_name',
    ...
}

dic = your_dict

# Can't iterate over collection being modified,
# so change the iterable being iterated.
for old, new in name_mapping.iteritems():
    value = dic.get(old, None)
    if value is None:
        continue

    dic[new] = value
    del dic[old]

Upvotes: 1

Related Questions