如何在Python字典中为键保留原值并添加列表结构?
Ah, I see the issue here—you’re overwriting the value of key entirely each time you assign to it, instead of nesting the original value and the list together in a sub-dictionary. Let’s fix that step by step:
The goal is to have key point to a dictionary that holds both your original numeric value and the list of sub-dictionaries. Here’s how to do it correctly:
First, initialize your empty dictionary, then set key to a structured dictionary right away (or update it later to include both parts):
result = {} # Set 'key' to a dict containing both the original value and an empty list result['key'] = {'数值': 20, '列表': []} # Now append your sub-dictionaries to the '列表' key inside 'key' result2 = {'7219': '0.49954929481682875'} result['key']['列表'].append(result2) result3 = {'1416': '0.48741579334133667'} result['key']['列表'].append(result3)
After running this code, your result dictionary will match exactly the structure you want:{'key': {'数值': 20, '列表': [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}]}}
The mistake in your original code was that when you did result['key'] = [], you replaced the existing value (20) with an empty list. By instead making key point to a dictionary that contains both the number and the list, you can keep both pieces of data without overwriting anything.
内容的提问来源于stack exchange,提问作者Jennifer Therese

