首页 > 解决方案 > 如何将字典列表添加到另一个字典?

问题描述

我有这本带键的字典“属性”,livenessTests而它又livenessTests是一个字典列表。如何添加/附加livenessTests到另一个字典json

properties = {

'livenessTests': [

{

'name':'http' + '_' + 'livenesstest',

'testObject':'/default.html'

},

{

'name':'https' + '_' + 'livenesstest',

'testObject':'/default.html'

}
]

生成的“json”目录应该类似于

json : {

"acg": {

"id": "1.87",

"name": "Internal"

},

"asmappings": [],

"cidrMaps": [],

"properties": {"livenessTests" : [{<contents from list above>},
                                  {<contents from list above>}
                                 ] 

              }

我正在尝试这个

for key in properties.keys():
    print key
    json['properties'].append(property[key])

我收到此错误,

> json['properties'].append(properties[key])

KeyError: 'properties'

我在这里做错了什么?抱歉刚开始学习。谢谢

标签: pythondictionary

解决方案


使用字典更新方法。

json.update(properties)

例子:

properties = {    
'livenessTests': [
    {'name':'http' + '_' + 'livenesstest',
    'testObject':'/default.html'
    },
    {
    'name':'https' + '_' + 'livenesstest',
    'testObject':'/default.html'
    }
]}

json = {"acg": {
    "id": "1-7KLGU.G19717",
    "name": "Akamai Internal-1-7KLGU - 1-7KLGU.G19717"
    },
    "asmappings": [],
    "cidrMaps": [],
    "livenessTests" : []
    }

json.update(properties)
print json

推荐阅读