Search code examples
pythondictionaryfor-loopreturn

How to append values to a python dictionary and return it in a function call


I have a for loop within a python function call that executes a number of times. I need to return the values in a dictionary to dump them into a db.

Here is a piece of sample code, how can I append values to a dictionary and ensure I have all of them for further use.

def parser_code():
    log = dict()
    for i in range(len):
        log['abc'] = 2*i
        log['xyz'] = 10+i
    return log

This will execute atleast twice so I want a dictionary to be log = {['abc':2, 'xyz':11],['abc':3, 'xyz':12]}

How can I append to the result each time? Or is there a smarter way to do this?


Solution

  • I'm not 100% sure what behavior you're expecting, but I think this code should suffice:

    def parser_code(length):
      log = list()
      for i in range(length):
        this_dict = dict()
        this_dict['abc'] = 2*i
        this_dict['xyz'] = 10+i
        log.append(this_dict)
      return log