简体   繁体   English

如何将值附加到python字典并在函数调用中返回

[英]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. 我在执行多次的python函数调用中有一个for循环。 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]} 这将至少执行两次,所以我希望字典为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? 还是有更聪明的方法来做到这一点?

I think you are looking for defaultdict part of std-libs. 我认为您正在寻找std-libs的defaultdict部分。

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)

I'm not 100% sure what behavior you're expecting, but I think this code should suffice: 我不确定您期望的行为是100%,但是我认为这段代码就足够了:

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

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). 请不要因为您的代码对我不起作用(for循环的原始缩进-现在已更正)和len参数)。 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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM