【问题标题】:Combine dictionary from a loop update statement从循环更新语句中组合字典
【发布时间】:2020-05-22 10:25:25
【问题描述】:

这是我当前的代码

import copy
modes = ['dry', 'cool', 'heat']
result = {}

result['definition'] = [{'dtype': '', 'label': '', 'value': ''}]
    for mode in modes:
    for i in result['definition']:
        for mode in modes:
            ii = copy.deepcopy(i)
            ii.update(dict(dtype='mode', label=mode, value=0))
            print ii

这是我的结果

{'dtype': 'mode', 'value': 0, 'label': 'dry'}
{'dtype': 'mode', 'value': 0, 'label': 'cool'}
{'dtype': 'mode', 'value': 0, 'label': 'heat'}

我希望我的输出看起来像这样

result['definition'] = [{'dtype': 'mode', 'label': 'dry', 'value': 0}, 
                        {'dtype': 'mode', 'label': 'cool', 'value': 0}, 
                        {'dtype': 'mode', 'label': 'heat', 'value': 0}]

你能给我建议吗?提前致谢! :)

【问题讨论】:

  • 您的代码输出与您在问题中打印的输出不同。

标签: python python-3.x list python-2.7


【解决方案1】:

试试这个

import copy
modes = ['dry', 'cool', 'heat']
result = {}

result['definition'] = [{'dtype': '', 'label': '', 'value': ''}]

result1 = dict()
result1 = {'definition':[]}
for i in result['definition']:
  for mode in modes:
    ii = copy.deepcopy(i)
    ii.update(dict(dtype='mode', label=mode, value=0))
    result1['definition'].append(ii)
print (result1['definition'])

【讨论】:

  • 您好,感谢您的帮助。我觉得它很有帮助,但它会重复我在模式上输入的数量。
  • 你可以先去掉for循环,没必要,我也会更新答案
猜你喜欢
  • 1970-01-01
  • 2014-07-18
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多