0

I'm a new to python and I need some help with one loop. Here is the code:

def show_result(self):
    listed = self.listed
    res = {}

    for key in listed:
        query_result = 0
        is_listed = 0
        rbl = key

        if not listed[key].get('ERROR'):
            query_result = "success"
            if listed[key]['LISTED']:
                is_listed = 1
            else:
                is_listed = 0
        else:
            query_result = "error"
            pass

        res[key] = [ ['rbl', rbl], ['host', listed['SEARCH_HOST']], ['lookup', query_result], ['is_listed', is_listed] ]

    return res


try:
    con = db.connect(db_server, db_user, db_password, db_name)
    cur = con.cursor()

    #hosts = json array with Hosts and IP's
    for host in hosts:
        searcher = checkHost(host, rbls, report)
        result = searcher.show_result()

        #
        # Need to loop through result to get rbl, host, lookup and is_listed variables
        # to be able to execute the query and commit it later when loop is finished
        #
        cur.execute("INSERT INTO checks_reports_df8 (`rbl`, `host`, `lookup`, `is_listed`) VALUES(%s, %s, '%s')", (rbl, host, lookup, is_listed)) 

    con.commit()

except db.Error, e:
    if con:
        con.rollback()
finally:
    if con:
        con.close()

If I pprint result from searcher.show_result() here is what I've get:

{u'0spam-killlist.fusionzero.com': [['rbl', u'0spam-killlist.fusionzero.com'],
                                ['host', u'127.0.0.2'],
                                ['lookup', 'success'],
                                ['is_listed', 0]],
u'zen.spamhaus.org': [['rbl', u'zen.spamhaus.org'],
                   ['host', u'127.0.0.2'],
                   ['lookup', 'success'],
                   ['is_listed', 1]]}

My problem is that I don't know how to loop through the result from searcher.show_result(). If my approach is wrong, the result returned from searcher.show_result() can be changed.

Milen Mihalev
  • 350
  • 1
  • 7
  • 21
  • 2
    That's a dictionary, so see https://docs.python.org/2/tutorial/datastructures.html#dictionaries – jonrsharpe Nov 14 '14 at 09:22
  • possible duplicate of [Iterating over Dictionaries...For Loops in Python](http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-for-loops-in-python) – Matt Nov 14 '14 at 09:23
  • why don't you try the json module? https://docs.python.org/2/library/json.html – gunzapper Nov 14 '14 at 09:52

0 Answers0