我有一个带有三个(variable)项目的字典:

d = {"data": [1, 2, 3, 4], "id": 4, "name": "bob"}

我想在不复制任何数据的情况下将其分为两个命令。基本上,我想将idname密钥删除到其自己的字典中,但仅通过指定"I want all keys that aren't the "DATA“键”。

我想避免复制"data" key-value项目,因为它的尺寸可能为15+MB,因此,请提取其他项目并保持"data" key-value项目的完整。

我的尝试:

# This will create a new dict for the non "data" key items. Great!
# But I want the "data" key-value pair to remain in its own dictionary without having to copy it into a new dict
non_data_dict = {key: d[key] for key in d.keys() - ['data']}

我期望的结果:

data_dict = {"data": [1,2,3,4]}
non_data_dict = {"id": 4, "name": "bob"}
分析解答

data pop呢?

data_dict = {"data": d.pop("data")}; non_data_dict = d

输出 :

print(f"{data_dict=}", f"{non_data_dict=}", sep="\n")

data_dict={'data': [1, 2, 3, 4]}
non_data_dict={'id': 4, 'name': 'bob'}