【问题标题】:Inserting dictionary objects into specific elements of an array (Python/Django)将字典对象插入到数组的特定元素中(Python/Django)
【发布时间】:2012-11-28 21:28:38
【问题描述】:

我的 Python 代码从数据库中获取数据,如下所示:

for result in request.user.results.all():
    data.append(dict([(str(word.type.type), str(word.word)) for word in result.word.all()
    data.append(dict([(season, ResultForm.CHOICES[r.season][1])]))

将“数据”显示为:

[{'color': 'blue', 'kind': 'pencil', 'rating': 'high'}, {'color': 'red', 'kind': 'truck', 'rating': 'low'}, {'season': 'winter'}, {'season': 'spring'}]

如何调整代码,使数据输出如下所示:

[{'color': 'blue', 'kind': 'pencil', 'rating': 'high', 'season': 'winter'}, {'color': 'red', 'kind': 'truck', 'rating': 'low', 'season': 'spring'}]

不只是添加最后一个对象,而是将它添加到每个元素中。

【问题讨论】:

  • 我不知道。您如何知道要将新数据添加到哪个字典?
  • 在我看来您想将季节键/值合并到结果字典中,但是您怎么知道 result.word.all() 的排序与 score 相同?你的第二个data.append() 似乎没有被锁定到循环中的任何内容,除非r.season 应该是result.season。即使如此,您提供的代码片段也没有说明为什么 score 应该以任何方式与您的结果查询集相关联。
  • 对不起,分数应该是赛季。
  • 为什么不把它写成一个干净的、逐步的过程呢?这样,你现在就可以修复它,甚至明年再理解它。尽管这些单线支架很好,但在许多情况下它们并不能编写出良好的可维护代码。

标签: python django arrays dictionary


【解决方案1】:

我想你想在这里dict.update。但是,我有点不确定在哪里插入dict.update,因为我不知道你的代码是如何工作的——在我看来你的输出应该是这样的:

[{'color': 'blue', 'kind': 'pencil', 'rating': 'high'}, {'season': 'winter'}, {'color': 'red', 'kind': 'truck', 'rating': 'low'},  {'season': 'spring'}]

由于“季节”字典是在另一个(“颜色”等)字典之后立即添加的......


附注:

dict([(score, ResultForm.CHOICES[r.season][1])])

必须更容易理解(和有效)地写成:

{score: ResultForm.CHOICES[r.season][1]}

如您的 cmets 所示,我相信您想要这样的东西:

for result in request.user.results.all():
    data.append(dict((str(word.type.type), str(word.word)) for word in result.word.all()))
    data[-1].update( {score: ResultForm.CHOICES[r.season][1]} )

【讨论】:

  • 我希望将季节字典包含在第一个字典中,如我的第二个样本集中所示。
  • 但是哪一行创建了season 字典?如果是第二行data.append,那么我相信你说的结果顺序是错误的。
  • 是的,很抱歉没有说清楚;它是创建季节的第二个追加
  • data[-1].update( {score: ResultForm.CHOICES[r.season][1]} 有效!谢谢
猜你喜欢
  • 1970-01-01
  • 2016-11-05
  • 2011-03-22
  • 2014-06-16
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
相关资源
最近更新 更多