在PYTHON中字典输出没有达到预期的水平 [英] In dictionary output is not getting as expected in PYTHON

查看:175
本文介绍了在PYTHON中字典输出没有达到预期的水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里在具有存储在字典中的表单值的字典中的响应。我的输出是单独的字典,我不需要分开。我想要一个字典中的所有元素

here response in an dictionary which is having form values stored in an dictionary. My output is generatd with seperate dictionary which i doesnot need seperately. I want all the elements in one dictionary only

resp = {}
b = []
for i in range(1, 10):
    resp_i = form.getvalue('opt_%d' %i, '0')
    resp[i] = int(resp_i)
    arg =  {i : resp[i]}
    b.append(arg)
    #print len(b)
for each in b:
    print each

实际输出:{1:1} {2:1} {3:3} {4:1} {5:3} { 6:0} {7:0} {8:0} {9:0}

Actual Output: {1: 1} {2: 1} {3: 3} {4: 1} {5: 3} {6: 0} {7: 0} {8: 0} {9: 0}

预期输出:{1:1,2:1,3: 4:1,5:3,6:0,7:0,8:0,9:0}

Expected output: {1: 1, 2: 1, 3: 3, 4: 1, 5: 3, 6: 0, 7: 0, 8: 0, 9: 0}

推荐答案

问题在这里:

b = []
for ...
   arg = {i: resp[i]}  # creates a new dict
   b.append(arg)  # adds the dict to the list

您可能想要的是:

b = {}
for ...
    b.update(arg)

当然这还不是最干净的方式来做我吨。毕竟,为什么要创建所有的临时字典?

Of course, this still isn't the cleanest way to do it. After all, why create all the temporary dictionaries?

b = {}
for ...
   b[i] = resp[i]

会工作,或者你甚至可以把它全部变成字典理解。

would work, or you could probably even pull it all into a dictionary comprehension.

这篇关于在PYTHON中字典输出没有达到预期的水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆