You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python字典中为键保留原值并添加列表结构?

Solution to Preserve Original Value and Add List of Sub-Dictionaries

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:56:15