如何在Python中创建符合指定格式的多维字典?
问题描述
尝试创建符合预期格式的多维字典,运行以下代码后输出不符合预期:
# existing dictionary models = {'sss':{'a':1, 'b':2}, 'xxx':{'c':3, 'd':4}} # using keys 'sss' from the models dictionary to iterate for m in models: s_data = {m: {}} specs = ['apple', 'cat', 'tomato'] for spec in specs: if 'apple' in spec: s_data[m]['fruit'] = spec if 'cat' in spec: s_data[m]['animal'] = spec if 'tomato' in spec: s_data[m]['vegetable'] = spec print(s_data)
预期输出:
{'sss': {'fruit': 'apple', 'animal':'cat', 'vegetable': 'tomato'}, 'xxx': {'fruit': 'apple', 'animal':'cat', 'vegetable': 'tomato'}}
错误原因
原代码核心问题是每次循环都重新初始化s_data = {m: {}},这会覆盖之前循环生成的键值对,最终仅保留最后一次循环的结果(即xxx对应的子字典)。
正确实现
有两种简洁的实现方式:
方式一:先初始化空字典,再逐个填充
models = {'sss':{'a':1, 'b':2}, 'xxx':{'c':3, 'd':4}} s_data = {} # 预先生成通用子字典内容 spec_mapping = { 'fruit': 'apple', 'animal': 'cat', 'vegetable': 'tomato' } for m in models: s_data[m] = spec_mapping.copy() # 用copy避免所有键指向同一个字典对象 print(s_data)
方式二:利用字典推导式(更简洁)
models = {'sss':{'a':1, 'b':2}, 'xxx':{'c':3, 'd':4}} s_data = { m: {'fruit': 'apple', 'animal':'cat', 'vegetable': 'tomato'} for m in models } print(s_data)
两种方式的输出均符合预期。
内容的提问来源于stack exchange,提问作者Harsha_02
相关产品推荐
相关产品推荐

