Reputation: 119
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?
Upvotes: 0
Views: 2455
Reputation: 1360
I think you are looking for defaultdict
part of std-libs.
from collections import defaultdict
glog = defaultdict(list)
def parser_code(dd):
for i in range(length):
dd['abc'].append(2*i)
return dd
glog = parser_code(glog)
if you actually want to use your result you have to have make sure that the dict is not created new for every call to your function.
still a bit unclear if you need a dict or not, you will only need that if you want the ability for key-lookup. If you are happy with just making a list (array) of numbers, then go ahead and use a list.
glog = list()
def parser_code(lst):
return lst + [2*i for i in range(length)]
glog = parser_code(glog)
Upvotes: 2
Reputation: 3671
you can give the dictionary as a parameter to your function.
please not that your code is not working for me (original indention of the for loop - it's corrected now) and the len parameter). I needed to guess a little bit what you are actually doing. Could you take a look at your example code in the question or comment here?
def parser_code(result, length):
for i in range(length):
result['abc'] = 2*i
result['xyz'] = 10+i
return result
d = {}
parser_code(d, 3)
print(d)
parser_code(d, 3)
print(d)
will give this output:
python3 ./main.py
{'abc': 4, 'xyz': 12}
{'abc': 4, 'xyz': 12}
Upvotes: -1
Reputation: 573
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
Upvotes: 2