Py学习  »  Python

python中从公共密钥字典到单个字典的转换

Max • 3 年前 • 1146 次点击  

我有一个输入请求,它由多个字典组成,这些字典的键和值与字典相似。

这是我的意见。

req = {"main1": 
    {"x": {"a":220},"y": {"b":66}},
    "main2": 
    {"x": {"c":"1000","d":"copper"},
    "y": {"c":"1200","d":"Copper"}}}
    

我需要的输出:

{'cable1': {'a': 220, 'c': '1000', 'd': 'copper'}, 'cable2': {'b': 66, 'c': '1200', 'd': 'Copper'}}

以下是我的尝试:

actual_req = []
for attr1, attr2 in req.items():
    for j, k in attr2.items():
        actual_req.append(k)
actual_req[0].update(actual_req[2])
actual_req[1].update(actual_req[3])
data = {'cable1': actual_req[0], 'cable2': actual_req[1]}

print(data)

简而言之,我只需要更通用的写作方式。它还应该使用

req = {"main1": 
    {"x": {"a":220},"y": {"b":66}},
    "main2": 
    {"x": {"c":"1000","d":"cooper"},
    "y": {"c":"1200","d":"Copper"}},
     "main3": 
    {"x": {"e":20},"y": {"f":6}}}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131206
 
1146 次点击  
文章 [ 1 ]  |  最新文章 3 年前