[英]Replace character in dict keys recursively
I'm current working a script that takes an Android application's metadata as a nested dictionary and inserts it to MongoDB.我目前正在编写一个脚本,该脚本将 Android 应用程序的元数据作为嵌套字典并将其插入到 MongoDB。 However, since some of the keys include '.'
但是,由于某些键包含'.'
s (due to component names in the APK file), which unfortunately isn't accepted by MongoDB in the version being dealt with. s(由于 APK 文件中的组件名称),不幸的是,MongoDB在正在处理的版本中不接受它。 Currently trying to write a recursive script which replace the '.'
目前正在尝试编写一个递归脚本来替换'.'
s to '/'
s of the keys in the dict data being inserted, but some keys still aren't changed to fit the requirements. 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
Example input:示例输入:
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"}}
Any idea as to what might be missing?关于可能缺少什么的任何想法?
after the editing I understood your question more properly, the recursion solution for unknown amount of nested dicts is as below:编辑后我更正确地理解了你的问题,未知数量的嵌套字典的递归解决方案如下:
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))
output:输出:
{'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'}}
very good question.很好的问题。 like the coding and debugging!喜欢编码和调试!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.