【发布时间】:2021-04-06 14:47:38
【问题描述】:
我有这段代码,我用它来将结构中包含列表的字典转换为字典列表,为内部列表的每个项目添加平面结构中的新列。这是我的代码:
origin = {
"a":1,
"b":2,
"m":[
{"c":3},
{"c":4}
]
}
# separating the "flat" part of the structure
flat = dict()
for o in origin.keys():
if not isinstance(origin[o], list):
flat[o] = origin[o]
lines = list()
# starts receiving the 'flat' value, once the new lines will receive the same flat values.
new_line = flat
# getting the "non-flat" values and creating new dictionaries using the flat structure
for i in origin["m"]:
k = list(i.keys())[0]
v = list(i.values())[0]
new_line[k] = v
print(f"NEW_LINE: {str(new_line)}")
lines.append(new_line)
print(f"LINES:\n{str(lines)}")
我期待这个:
NEW_LINE: {'a': 1, 'b': 2, 'c': 3}
NEW_LINE: {'a': 1, 'b': 2, 'c': 4}
LINES:
[{'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 4}]
但我明白了:
NEW_LINE: {'a': 1, 'b': 2, 'c': 3}
NEW_LINE: {'a': 1, 'b': 2, 'c': 4}
LINES:
[{'a': 1, 'b': 2, 'c': 4}, {'a': 1, 'b': 2, 'c': 4}]
为什么?
【问题讨论】:
-
你需要在字典后面附加一个
copy:lines.append(new_line.copy()),否则它们都指向同一个对象。 -
非常感谢@KrishnaChaurasia!