简体   繁体   English

从模板字典和键生成字典列表

[英]generate list of dictionaries from template dictionary and keys

I'm trying to automate a series of tests, and I need to have a loop where I change the parameters. 我正在尝试使一系列测试自动化,并且需要有一个循环来更改参数。

mydictionary={'a':10,'b':100,'c':30}

def swapRules(d,rule):
   "clear dict, set to 100 the rule that match the string"
   print d, rule
   if not d.has_key(rule): raise Exception("wrong string")
   d=resetDict(d)
   d[rule]=100
   return d

def resetDict(d):
   '''clear the dict '''
   for i in d.keys():
       d[i]=0
   return d

def tests(d):
   from itertools import starmap, repeat, izip
   keys=d.keys()
   paramsDictionaries=list(starmap(swapRules, izip(repeat(d),keys)))
   print(paramsDictionaries)

I'cannot understand why when I run test(mydictionary) the output always contains the same value. 我不明白为什么当我运行test(mydictionary)时输出总是包含相同的值。 Seems that the issue is not in a wrong use of the itertools: as the REPL shows by substituting with a simple list comprehension: 似乎问题不在于对itertools的错误使用:如REPL所示,用简单的列表理解代替:

In [9]: keys=mydictionary.keys()
In [10]: [tr.swapRules(mydictionary,jj) for jj in keys]
{'a': 0, 'c': 0, 'b': 100} a
{'a': 100, 'c': 0, 'b': 0} c
{'a': 0, 'c': 100, 'b': 0} b
Out[10]:
[{'a': 0, 'b': 100, 'c': 0},
 {'a': 0, 'b': 100, 'c': 0},
 {'a': 0, 'b': 100, 'c': 0}]

I'm really puzzled since when the swapRules function is evoked alone, produces the expected result, as shown by the print statements... any idea on what I'm doing wrong? 我真的感到很困惑,因为当单独调用swapRules函数时,会产生预期的结果,如print语句所示...对我做错的事情有任何想法吗? is it by any chance caching something? 是不是偶然缓存了一些东西?

Answering my own question since I've found that this work: 自从发现这项工作以来,回答我自己的问题:

def swapRules2(d,rule):
    '''clear dict, return new with only rule set'''
    keys=d.keys()
    if rule not in keys: raise Exception("wrong key")
    outd=dict.fromkeys(keys,0)
    outd[rule]=100
    return outd

and in the list comprehension it returns the expected output: 并在列表理解中返回预期的输出:

 In [16]: [tr.swapRules2(mydict,jj) for jj in keys]
Out[16]:
[{'a': 100, 'b': 0, 'c': 0},
 {'a': 0, 'b': 0, 'c': 100},
 {'a': 0, 'b': 100, 'c': 0}]

However, I still do not understand why the previous approach did not. 但是,我仍然不明白为什么以前的方法没有。

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

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