[英]replace dictionary keys (strings) in Python
CSV導入后,我使用不同語言的密鑰跟隨字典:
dic = {'voornaam': 'John', 'Achternaam': 'Davis', 'telephone': '123456', 'Mobielnummer': '234567'}
現在我想將鍵更改為英語(也是全部小寫)。 應該是:
dic = {'first_name': 'John', 'last_name': 'Davis', 'phone': '123456', 'mobile': '234567'}
我怎樣才能做到這一點?
你有字典類型,它非常適合
>>> 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]
如果輸入dict中沒有嵌套的字典對象,則上述解決方案效果很好。
下面是更通用的實用程序函數,它以遞歸方式用新的鍵集替換現有的鍵。
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'
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.