【问题标题】:Recursive iteration and modification of dictdict的递归迭代和修改
【发布时间】:2014-12-18 12:20:29
【问题描述】:

我有一个像这样的JSON 文件:

{
    "top_key1": {
                "bottom.key1": "one",
                "bottom.key2": "two"
                },
    "top_key2": [
                "bottom.key1": "one",
                "bottom.key2": "two",
                ]
}

而且我需要存储在不允许我存储带有句点 (.) 的密钥的数据结构中。如何遍历这个JSON 结构,以便将每个. 替换为_?最终结果是:

{
    "top_key1": {
                "bottom_key1": "one",
                "bottom_key2": "two"
                },
    "top_key2": [
                "bottom_key1": "one",
                "bottom_key2": "two",
                ]
}

JSON 文件可以嵌套多次(未知),值也可以有.,但我不希望它们被_ 替换。另外,“top_key2”的值是一个列表,应该保留。

【问题讨论】:

标签: python


【解决方案1】:

我觉得不太难,只要用isinstance 来检查当前值是否是另一个字典:

nested_dict = {
    "top_key1": {
                "bottom.key1": "one",
                "bottom.key2": "two"
                },
    "top_key2": {
                "bottom.key1": "one",
                "bottom.key2": "two",
                }
}

def replace_dots(nested_dict):
    result_dict = {}
    for key, val in nested_dict.items():
        key = key.replace('.', '_')
        if isinstance(val, dict):
            result_dict[key] = replace_dots(val)
        else:
            result_dict[key] = val
    return result_dict

fixed = replace_dots(nested_dict)

fixed
Out[4]: 
{'top_key1': {'bottom_key1': 'one', 'bottom_key2': 'two'},
 'top_key2': {'bottom_key1': 'one', 'bottom_key2': 'two'}}

我不确定我是否完全理解您的编辑,例如您的示例列表 仍然有一个键值结构,但增加了一个额外的案例来处理 使用列表非常简单:

nested_dict2 = {
    "top_key1": {
                "bottom.key1": "one",
                "bottom.key2": "two"
                },
    "top_key2": ["list.item1", "list.item2"]
}

def replace_dots(nested_dict):
    result_dict = {}
    for key, val in nested_dict.items():
        key = key.replace('.', '_')
        if isinstance(val, dict):
            result_dict[key] = replace_dots(val)
        elif isinstance(val, list):
            cleaned_val = [v.replace('.', '_') for v in val]
            result_dict[key] = cleaned_val
        else:
            result_dict[key] = val
    return result_dict

replace_dots(nested_dict2)
Out[7]: 
{'top_key1': {'bottom_key1': 'one', 'bottom_key2': 'two'},
 'top_key2': ['list_item1', 'list_item2']}

【讨论】:

  • 谢谢马吕斯。 JSON 对象上还有列表,以及带有句点的键,因此该方法缺少该特定用例。
  • @licorna:请参阅我的编辑,您可以添加额外的类型检查来处理列表,尽管您问题中的示例列表对我来说作为 JSON 并不完全有意义,所以我采取了有点猜测你的意思。
猜你喜欢
  • 2011-11-14
  • 1970-01-01
  • 2021-12-24
  • 2015-04-20
  • 2016-06-14
  • 2012-10-17
  • 2019-12-10
  • 2019-02-19
  • 1970-01-01
相关资源
最近更新 更多