在Python中替换字典键(字符串)

时间:2013-07-29 20:04:32

标签: python dictionary

CSV导入后,我使用不同语言的密钥跟随字典:

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

现在我想将密钥更改为英文(也是全部小写)。应该是:

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

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:24)

你有字典类型,它完全适合

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

答案 1 :(得分: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]

答案 2 :(得分:1)

如果输入词典中没有嵌套的词典对象,则上述解决方案效果很好。

下面是更通用的实用程序函数,它以递归方式用新的键集替换现有的键。

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

测试:

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

输出:

{
'test': {
    'last_name': 'Davis'
},
'mobile': '234567',
'first_name': 'John',
'last_name': 'Davis',
'phone': '123456'
}
相关问题