简体   繁体   English

在Python中更改字典顺序(Django)

[英]Changing dictionary ordering in Python (Django)

I have Python code accessing data in a database (in Django): 我有Python代码访问数据库中的数据(在Django中):

for result in request.user.results.all():
    for word in result.word.all():
        data.append(dict(zip([str(word.type.type)], [str(word.word)])))

which displays 'data' as such: 它显示'数据'如下:

[{'color': 'blue'}, {'kind': 'pencil'}, {'rating': 'high'}, {'color': 'red'}, {'kind': 'truck'}, {'rating': 'low'} and so on....

I want to rewrite the python code to display this instead: 我想重写python代码来显示它:

[{'color': 'blue', 'kind': 'pencil', 'rating': 'high'}, {'color': 'red', 'kind': 'truck', 'rating': 'low'} and so on....

Are these two the same or does the location of the '{' matter? 这两个是相同的还是'{'的位置? I wrote the code above but I'm not how (or if I need to) modify it. 我写了上面的代码,但我不是如何(或者如果我需要)修改它。

It looks to me like your zipping together single-item lists to make single item dicts. 在我看来,你喜欢将单项目列表压缩在一起制作单项目。 I think what you want instead is: 我想你想要的是:

for result in request.user.results.all():
    data.append(dict([(word.type.type, word. word) for word in result.word.all()]))

zip is typically used to make dicts in situations when you have two pre-existing lists, not so much when you're constructing a dict from scratch from objects. zip通常用于在你有两个预先存在的列表的情况下制作dicts,而不是在你从头开始从对象构造一个dict时。

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

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