我正在尝试从已经创建的字典创建嵌套字典。在我的字典中,每个键都有一个值列表。我想向这些值添加一个附加键,然后创建一个新的键和值对,该值来自先前所有这些值的原始键。如果相关的话,我还将根据另外两个字典生成字典(对不起,我很难解释)
用于编写原始字典的代码
dict1 = cls.make_ssc()
dict2 = cls.make_tg()
dictfinal = {}
for key in dict1.keys():
dictfinal[key] = [dict1[key], dict2[key]]
return dictfinal
这就是我现在所拥有的:
{'blue':['dog','carrot'],'red':['cat','peas'],'yellow':['elephant','硬花甘蓝'],}
我要这样做:
{'blue':{'color':'blue','animal':'dog','vegetable':'carrot'},'red':{'color':'red', 'animal':'cat','vegetable':'peas'},'yellow':{'color':'yellow','animal':'elephant','vegetable':'硬花甘蓝'},} } strong>
答案 0 :(得分:0)
好像您需要dict
和zip
例如:
dictfinal = {}
keys = ['color', 'animal', 'vegetable']
for key in dict1.keys():
dictfinal[key] = dict(zip(keys, [key, dict1[key], dict2[key]]))
return dictfinal