在嵌套字典中添加键值

时间:2020-07-06 04:31:38

标签: python list dictionary nested

datainput = {'thissong-fav-user:type1-chan-44-John': [{'Song': 'Rock',
                                                       'Type': 'Hard',
                                                       'Price': '10'}],
             'thissong-fav-user:type1-chan-45-kelly-md': [{'Song': 'Rock',
                                                           'Type': 'Soft',
                                                           'Price': '5'}]}

必需的输出:

{'thissong-fav-user:type1-chan-44-John': [{key:'Song',Value:'Rock'},
                                          {key:'Type', Value:'Hard'},
                                          {Key: 'Price', Value:'10'}],
 'thissong-fav-user:type1-chan-45-kelly-md': [{key:'Song',Value:'Rock'},
                                              {key:'Type', Value:'Soft'},
                                              {Key: 'Price', Value:'5'}]}

我从下面开始,这给了我一个内部嵌套的模式,不确定我如何获得期望的输出。

temps = [{'Key': key, 'Value': value} for (key, value) in datainput.items()] 

2 个答案:

答案 0 :(得分:1)

方法如下:

datainput = {'thissong-fav-user:type1-chan-44-John': [{'Song': 'Rock',
                                                       'Type': 'Hard',
                                                       'Price': '10'}],
             'thissong-fav-user:type1-chan-45-kelly-md': [{'Song': 'Rock',
                                                           'Type': 'Soft',
                                                           'Price': '5'}]}
temps = {k:[{'Key':a, 'Value':b}
            for a,b in v[0].items()]
         for k,v in datainput.items()}

print(datainput)

输出:

{'thissong-fav-user:type1-chan-44-John': [{'Key': 'Song', 'Value': 'Rock'},
                                          {'Key': 'Type', 'Value': 'Hard'},
                                          {'Key': 'Price', 'Value': '10'}],
 'thissong-fav-user:type1-chan-45-kelly-md': [{'Key': 'Song', 'Value': 'Rock'},
                                              {'Key': 'Type', 'Value': 'Soft'},
                                              {'Key': 'Price', 'Value': '5'}]}

答案 1 :(得分:1)

我相信采用输入的方式很好,但是为了获得所需的输出,您必须首先采用输入,然后采用键值对,最后进行迭代。

datainput = {'thissong-fav-user:type1-chan-44-John': [{'Song': 'Rock',
                                                       'Type': 'Hard',
                                                       'Price': '10'}],
             'thissong-fav-user:type1-chan-45-kelly-md': [{'Song': 'Rock',
                                                           'Type': 'Soft',
                                                           'Price': '5'}]}
datainput = {k:[{'Key':a, 'Value':b} for a,b in v[0].items()] for k,v in datainput.items()}

print(datainput)

很有可能,您将以这种方式获得所需的输出。