unexpected output while using list(and nested dictionary)

Denis McMahon denismfmcmahon at gmail.com
Wed Jul 22 22:38:50 EDT 2015


On Wed, 22 Jul 2015 17:09:21 -0500, max scalf wrote:

> I have posted a question on stack overflow for better readability ...
> but is intended for python list.... Please see question below...

It's quite obvious that your list and dictionary processing is not doing 
what you think it is.

However, the question you have posted is a long and complex one. Perhaps 
you could reduce it to a simpler example.

Your problem seems to be that in a list of dictionaries that is itself 
several levels of dictionary deep, you only see a single dictionary when 
you do the json conversion.

perhaps you could try a simpler structure, such as:

import json

d1 = {'c':'0.0.0.0', 'f':'1', 'p':'icmp', 't':'1'}
d2 = {'c':'1.1.1.1', 'f':'22', 'p':'tcp', 't':'22'}
l = [d1,d2]
d3 = {'g': 'text', 's': l}
d4 = {'p': d3}
d5 = {'r': d4}
print d5
print json.dumps(d5)

This correctly gives the following output, so I guess your problem is in 
how you create the list of dictionaries (l in my example).

{'r': {'p': {'s': [{'p': 'icmp', 'c': '0.0.0.0', 't': '1', 'f': '1'}, 
{'p': 'tcp', 'c': '1.1.1.1', 't': '22', 'f': '22'}], 'g': 'text'}}}

{"r": {"p": {"s": [{"p": "icmp", "c": "0.0.0.0", "t": "1", "f": "1"}, 
{"p": "tcp", "c": "1.1.1.1", "t": "22", "f": "22"}], "g": "text"}}}

I would suggest you look closely at your makesg function, and the data 
that you are actually feeding to it and how it is using that data.

makesg expects a collection as the third param, you seem to be passing it 
a list of one port element.

makesg returns a list of sg, with an entry for every port. You then use 
this as tsg.SecurityGroupIngress. However, the way your code is written, 
you process all the 'i' in mylist, and for each 'i' overwrite 
tsg.SecurityGroupIngress with a new single element list sg from makesg.

I suspect you've refactored some code from processing a list of things 
inside a function to processing them in the main body, or vice versa, or 
have just got confused about what you're processing where.

I suggest that you rename your makesg function to makesgr, and have it 
return the rule appropriate to one entry in mylist.

Then you can append the returned rule to tsg.SecurityGroupIngress with:

tsg.SecurityGroupIngress.append(mksgr(param,param,param))

Alternatively, pass mylist to makesg, and return the whole list of rules.

tsg.SecurityGroupIngress = mksg(mylist)

Either method will require some rewriting of both the mksg[r] function 
and the main code to work together, but as the existing problem is that 
they don't seem to work together to create the data structure you expect 
them to create, that's not going to be a bad thing.

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list