json 如何从另一个嵌套字典创建Python嵌套字典

8ljdwjyq  于 2023-05-13  发布在  Python
关注(0)|答案(3)|浏览(159)

我想用python从另一个嵌套字典创建一个嵌套字典。下面是将作为python对象加载的示例json对象,我需要将输出作为另一个嵌套的dict。

{
    "latest": {
        "school": {
            "zip": 123,
            "city": 345,
            "degree": {
                "high": 1,
                "pre": 45
            }
        },
        "student": {
            "size": 345,
            "enroll": {
                "all": "abc",
                "grad": 1099
            }
        },
        "cost": {
            "booksupply": 1600,
            "tution": [1, 2, 4]
        }
    },
    "school_id": 1234,
    "location": {
        "lat ": 12.3,
        "lon ": 34.23
    }
}

---我的新字典应该看起来像下面,我只是删除了一些嵌套的键,因为我不需要它们,而不是改变级别或重新格式化键。例如:我删除了关键latest.school.zip latest.student.enroll latest.school.zip latest.cost.booksupply位置

{
    "latest": {
        "school": {
            "city": 345,
            "degree": {
                "high": 1

            }
        },
        "student": {
            "size": 345
        },
        "cost": {

            "tution": [1, 2, 4]
        }

    },
    "school_id": 1234
}

---我是python新手,因此不确定创建新字典的最佳方法是什么,假设这个dict中有4000个键(嵌套)需要删除,只有50个键将留在这个dict对象中,我不想输入所有的名字,更容易的方法是给予一个我想要保留的键列表,并使用这个键列表创建一个字典。
例如;(下面的语法不正确,我不确定嵌套键的正确语法是什么)。
key_needed = [latest.school.city.degree.high,latest.student.size,latest.student.cost.tution,school_id ]
---阅读json文件并创建新的dict。
f = open(json_file_path)data = json.load(f)new_dict = {x:data{x} for x in key_needed}
我不知道如何创建key_needed的列表时,键是嵌套的。如果上述方法不理想,请建议任何其他方法来创建新的dict。

6qfn3psc

6qfn3psc1#

您可以执行以下操作:

new_dict = {}
key_needed = ["latest.school.city", "latest.school.degree.high" , "latest.student.size", "latest.cost.tution", "school_id"]
for key in key_needed:
  cur_d = new_dict
  val = data
  levels = key.split('.')[:-1]
  if not levels:
    new_dict[key] = data[key]
    continue
  for k in levels:
    if cur_d.get(k, None) is None:
      cur_d[k] = {}
    cur_d = cur_d[k]
    val = val[k]
  cur_d[k] = val 
print(json.dumps(
    new_dict,
    indent=4,
    separators=(',', ': ')
))

:我假设每个点指的是一个级别。你的水平也有问题,我在key_needed中纠正了它们。

tjrkku2a

tjrkku2a2#

您可以使用python-box库删除不需要的所有内容。

from box import Box

nested_dict = {
    "latest": {
        "school": {
            "city": 345,
            "degree": {
                "high": 1

            }
        },
        "student": {
            "size": 345
        },
        "cost": {

            "tution": [1, 2, 4]
        }

    },
    "school_id": 1234
}

keys_to_delete = [
    "latest.school.degree.high",
    "latest.student.size",
    "latest.student.cost.tution",
    "school_id"
]

box = Box(nested_dict, box_dots = True)

for key in keys_to_delete:
    try:
        del box[key]
    except:
        # if the key is not existing
        pass

# the new dict
print(box.to_dict())
vngu2lb8

vngu2lb83#

使用del关键字

>>> test = {"foo": "bar", "foo1": "bar1"}
>>> del test["foo1"]
>>> test
{'foo': 'bar'}

或者尝试以下解决方案之一:https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/#

相关问题