【问题标题】:Add keys to values already inside a key and then add extra value and key based on key name将键添加到键中已有的值,然后根据键名添加额外的值和键
【发布时间】:2019-07-24 08:14:01
【问题描述】:

我正在尝试从我已经创建的字典创建嵌套字典。在我的每个键的字典中,我都有一个值列表。我想为这些值添加一个附加键,然后创建一个新的键值对,该值来自之前所有这些值的原始键。如果相关的话,我还会从其他两个字典生成字典(对不起,我很难解释)

用于制作原始字典的代码

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', 'broccoli'],}

我想做这个:

{'blue': {'color': 'blue', 'animal': 'dog', 'vegetable': 'carrot'}, 'red': {'color': 'red', '动物':'猫','蔬菜':'豌豆'},'黄色':{'颜色':'黄色','动物':'大象','蔬菜':'西兰花'},}强>

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    看起来你需要dictzip

    例如:

    dictfinal = {}
    keys = ['color', 'animal', 'vegetable']
    for key in dict1.keys():
          dictfinal[key] = dict(zip(keys, [key, dict1[key], dict2[key]]))
    return dictfinal
    

    【讨论】:

    • 完美运行!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多