簡體   English   中英

遞歸替換字典鍵中的字符

[英]Replace character in dict keys recursively

我目前正在編寫一個腳本,該腳本將 Android 應用程序的元數據作為嵌套字典並將其插入到 MongoDB。 但是,由於某些鍵包含'.' s(由於 APK 文件中的組件名稱),不幸的是,MongoDB在正在處理的版本中不接受它。 目前正在嘗試編寫一個遞歸腳本來替換'.' s 到正在插入的 dict 數據中的鍵的'/' s,但仍然沒有更改某些鍵以滿足要求。

def fixKeys(dictionary):
    for k,v in dictionary.items():
        if isinstance(v, dict):
            if '.' in k:
                dictionary[k.replace('.','/')] = dictionary.pop(k)
            fixKeys(v)
        else:
            if '.' in k:
                dictionary[k.replace('.','/')] = dictionary.pop(k)
    return dictionary 

示例輸入:

data = {"gender":"male","name.data": {"last.name":"Arabulut","first.name":"Altay","parents.names":{"father.name":"John","mother.name":"Jennifer"}}, "birthday.data":{"birthday.day":"01","birthday.month":"03","birthday.year":"1977"}}

關於可能缺少什么的任何想法?

編輯后我更正確地理解了你的問題,未知數量的嵌套字典的遞歸解決方案如下:

def fixKeys(dictionary):
    for k,v in list(dictionary.items()):
        if isinstance(v, dict):
            dictionary[k.replace('.', '/')] = fixKeys(v)
        else:
            dictionary[k.replace('.', '/')] = v
        if "." in k:
            dictionary.pop(k)
    return dictionary

m_dict = {"gender":"male", "name.data": {"last.name":"Arabulut","first.name":"Altay","parents.names":{"father.name":"John","mother.name":"Jennifer"}}, "birthday.data":{"birthday.day":"01","birthday.month":"03","birthday.year":"1977"}}

new_dict = fixKeys(m_dict)
print(str(new_dict))

輸出:

{'gender': 'male', 'name/data': {'last/name': 'Arabulut', 'first/name': 'Altay', 'parents/names': {'father/name': 'John', 'mother/name': 'Jennifer'}}, 'birthday/data': {'birthday/day': '01', 'birthday/month': '03', 'birthday/year': '1977'}}

很好的問題。 喜歡編碼和調試!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM