简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM