9

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?

2
  • 1
    Why downvotes? I think I need to know why so that I can improve the question. Commented Jul 29, 2013 at 20:08
  • The question doesn't show much research effort. For example, what approach(es) make sense to you? Have you attempted to implement any of them? What happened when you tried? Commented Jul 29, 2013 at 20:14

3 Answers 3

24

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'}
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think OP want to convert values to lowecase, am I missed something?
Yes indeed, I want keys to be English and all lowercase, not values.
1
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]

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.