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

时间:2013-07-11 18:31:37

标签: python dictionary list-comprehension

我正在尝试自动化一系列测试,我需要一个循环来更改参数。

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)

我不明白为什么当我运行test(mydictionary)时,输出总是包含相同的值。似乎问题不在于对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}]

我真的很困惑,因为当swapRules函数被单独引发时,会产生预期的结果,如print语句所示......对于我做错了什么的任何想法?是不是有机会缓存​​什么?

1 个答案:

答案 0 :(得分:0)

回答我自己的问题,因为我发现这项工作:

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

并在列表解析中返回期望的输出:

 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}]

但是,我仍然不明白为什么之前的方法没有。

相关问题