我面临一个奇怪的行为-变量无明显原因更改其值。请帮助我了解发生这种情况的原因/原因以及如何避免这种情况。下面以内嵌注释的形式给出了详细信息。为了方便起见,将打印语句添加到了代码中。
想法是通过乘以如下所示的高阶数据来展平json文件。
非常感谢。
"""
The expected output is:
[{'records': '563'},
{'records': '563', 'id': '1111111', 'title': 'alignable', 'status': 'Completed'},
{'records': '563', 'id': '2222222', 'title': ' no links', 'status': 'something'}]
"""
test_json = {"records": "563",
"campaign": [{"id": "1111111", "title": "alignable", "status": "Completed"},
{"id": "2222222", "title": " no links", "status": "something"}]
}
def data_multiplication(initial_nested_data):
out = [{}]
def data_multiplication_(nested_data):
if isinstance(nested_data, list) and len(nested_data) > 0:
base_dic = out[-1] # with the current example, this line should ( and is ) executed once only.
# The main question is how it happens that base_dic changes from [{'records': '563'}]
for x in nested_data:
print(f'The base_dictionary before the desired append is: {base_dic}')
# Works like a breeze when I append the out list with a static dic as below.
out.append({1: 'This here should be the basic dictionary'}) # Comment this line to switch
# Starts behaving abnormally if I append the out list as below.
# out.append(base_dic) # Uncomment this line to switch
print(f'The base_dictionary after the desired append is: {base_dic}')
data_multiplication_(x)
elif isinstance(nested_data, dict) or len(nested_data) == 0:
for x in nested_data:
if (isinstance(nested_data[x], list) or isinstance(nested_data[x], dict)) and len(nested_data[x]) > 0:
data_multiplication_(nested_data[x])
else:
out[-1][x] = nested_data[x]
data_multiplication_(initial_nested_data)
return out
if __name__ == '__main__':
result = data_multiplication(test_json)
答案 0 :(得分:0)
您似乎在使问题变得更加棘手,或者没有解释。给定您的示例输入和输出,这应该可以工作:
test_json = {
"records": "563",
"campaign": [
{"id": "1111111", "title": "alignable", "status": "Completed"},
{"id": "2222222", "title": " no links", "status": "something"}
]
}
def data_multiplication(initial_nested_data):
out = [{}]
def data_multiplication_recursive(nested_data):
if isinstance(nested_data, dict):
for key, value in nested_data.items():
if isinstance(value, list):
data_multiplication_recursive(value)
else:
out[0][key] = value
elif isinstance(nested_data, list):
base_dic = out[0]
for dictionary in nested_data:
out.append({**base_dic, **dictionary})
data_multiplication_recursive(initial_nested_data)
return out
if __name__ == '__main__':
result = data_multiplication(test_json)
print(result)
输出
[
{'records': '563'},
{'records': '563', 'id': '1111111', 'title': 'alignable', 'status': 'Completed'},
{'records': '563', 'id': '2222222', 'title': ' no links', 'status': 'something'}
]