Привет, я новый пользователь, но нашел ответ на тот же вопрос, я не могу получить ничего полностью функционального в своей проблеме, я делаю этот маленький кусочек торта с полной вложенной заменой ключей, вы можете отправить список диктовать или диктовать.
Наконец, у ваших диктов может быть список с вложенным диктатом или более, и все это заменяется вашими новыми ключевыми потребностями.
Чтобы указать, кто из ключей хочет заменить новым ключом, используйте параметр «to», отправляющий dict.
Смотри в конце мой маленький пример.
P / D: Извините, мой плохой английский. =) * * Тысяча одна
def re_map(value, to):
"""
Transform dictionary keys to map retrieved on to parameters.
to parameter should have as key a key name to replace an as value key name
to new dictionary.
this method is full recursive to process all levels of
@param value: list with dictionary or dictionary
@param to: dictionary with re-map keys
@type to: dict
@return: list or dict transformed
"""
if not isinstance(value, dict):
if not isinstance(value, list):
raise ValueError(
"Only dict or list with dict inside accepted for value argument.") # @IgnorePep8
if not isinstance(to, dict):
raise ValueError("Only dict accepted for to argument.")
def _re_map(value, to):
if isinstance(value, dict):
# Re map dictionary key.
# If key of original dictionary is not in "to" dictionary use same
# key otherwise use re mapped key on new dictionary with already
# value.
return {
to.get(key) or key: _re_map(dict_value, to)
for key, dict_value in value.items()
}
elif isinstance(value, list):
# if value is a list iterate it a call _re_map again to parse
# values on it.
return [_re_map(item, to) for item in value]
else:
# if not dict or list only return value.
# it can be string, integer or others.
return value
result = _re_map(value, to)
return result
if __name__ == "__main__":
# Sample test of re_map method.
# -----------------------------------------
to = {"$id": "id"}
x = []
for i in range(100):
x.append({
"$id": "first-dict",
"list_nested": [{
"$id": "list-dict-nested",
"list_dic_nested": [{
"$id": "list-dict-list-dict-nested"
}]
}],
"dict_nested": {
"$id": "non-nested"
}
})
result = re_map(x, to)
print(str(result))