By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,491 Members | 1,169 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,491 IT Pros & Developers. It's quick & easy.

How to add a lists of dictionaries to another dictionary?

P: 1
I have this dictionary "properties" with a key livenessTests and in turn the livenessTests is a list of dictionaries. How do I add/append livenessTests to another dictionary json?

Expand|Select|Wrap|Line Numbers
  1. properties = {
  2.  
  3. 'livenessTests': [
  4.  
  5. {
  6.  
  7. 'name':'http' + '_' + 'livenesstest',
  8.  
  9. 'testObject':'/default.html'
  10.  
  11. },
  12.  
  13. {
  14.  
  15. 'name':'https' + '_' + 'livenesstest',
  16.  
  17. 'testObject':'/default.html'
  18.  
  19. }
  20. ]
  21.  
The resulting "json" directory should be something like

Expand|Select|Wrap|Line Numbers
  1. json : {
  2.  
  3. "acg": {
  4.  
  5. "id": "1-7KLGU.G19717",
  6.  
  7. "name": "Akamai Internal-1-7KLGU - 1-7KLGU.G19717"
  8.  
  9. },
  10.  
  11. "asmappings": [],
  12.  
  13. "cidrMaps": [],
  14.  
  15. "properties": {"livenessTests" : [{<contents from list above>},
  16.                                   {<contents from list above>}
  17.                                  ] 
  18.  
  19.               }
I am trying this :


Expand|Select|Wrap|Line Numbers
  1. json['properties'] = []  
  2.  
  3. for key in properties.keys():
  4.     print key
  5.     json['properties'].append(property[key])
  6.  
But I am getting ,

Expand|Select|Wrap|Line Numbers
  1.  "livenessTests": [
  2.      {
  3.          "name": "http_livenessTest",
  4.          "testObject": "/default.html"
  5.      },
  6.      {
  7.          "name": "https_livenessTest",
  8.          "testObject": "/default.html"
  9.      },
so I am not getting the key 'properties' .
Can you tell me where I am wrong ?
1 Week Ago #1
Share this Question
Share on Google+
1 Reply


P: 5
The same way you would add any other object.

myDict = {}
myDict[“myList”] = []
That would add an empty list, whose key is “myList”, to the dictionary “myDict”.

You could also use the dict “update” method, as follows:

myDict.update( myList: [] )
or this way:

myDict.update( {‘myList’: []} )
Although the second method is more appropriate to add several key/value pairs or for merging two dictionaries.
1 Week Ago #2

Post your reply

Sign in to post your reply or Sign up for a free account.