【发布时间】:2011-06-06 06:19:23
【问题描述】:
谁能告诉我如何排序:
{'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}
进入
{'a': [1, 2, 3], 'b': ['blah', 'bhasdf', 'asdf'], 'c': ['one', 'two'],'d': ['asdf', 'wer', 'asdf', 'zxcv']}
? 谢谢!
更新 1,代码示例:
所以我在做语言学。一篇文章被分解为存储在数据库中的单词,并具有各种属性,包括 para ID 和 sentence ID。任务:尝试重建原始文本。
从 DB 中获取 500 个连续单词
words = Words.objects.all()[wordId:wordId+500]
# I first create paragraphs, through which I can loop later in my django template,
# and in each para will be a list of words (also dictionaries).
# So i am trying to get a dictionary with values that are lists of dictionaries.
# 'pp' i make just for shorthanding a long-named variable.
paras={}
para_high = para_low = words[0].belongs_to_paragraph
for w in words:
last_word = w
pp = w.belongs_to_paragraph
if pp >para_high:
para_high = pp
if pp < para_low:
para_low = pp
if pp in paras:
paras[pp].append(w)
else:
list = [w]
paras[pp] = list
# Since there are blank lines between paragraphs, in rebuilding the text as it
# looked originally, I need to insert blank lines.
# Since i have the ID's of the paragraphs and they go somewhat like that: 1,3,4,8,9
#(the gaps between 1 & 3 and 4 & 8 i have to fill in with something else,
# which is why i had para_low and para_high to loop the range.
isbr = True
for i in range(para_low, para_high+1):
if i in paras:
isbr = True
else:
if isbr:
paras[i]=['break']
isbr = False
else:
paras[i]=[]
然而,在这一点上,如果我尝试循环 dict 并重建文本,一些后面的 id'd 段落会出现在前面的段落之前,这就是不行。
更新2,循环代码:
{% for k,v in wording.iteritems() %}
{% if v[0] == 'break' %}
<br/>
{% else %}
</div><div class="p">{% for word in v %}{% if word.special==0%} {% endif %}<span class="word {% if word.special == 0%}clickable{% endif%}" wid="{{word.id}}" special="{{word.special}}" somethingElse={{word.somethingElse}}>{{ word.word }}</span>{% endfor %}
{% endif %}
{% endfor %}
【问题讨论】:
-
...为什么,确切地说,你想要这个吗?
-
我猜现在的代码说明了我为什么要这样做
-
"如果我尝试循环 dict 并尝试重建文本,一些后面的 id-d 段落会出现在前面的段落之前,并且不会这样做。"是的。所以使用
sorted()。真的,就这么简单。 -
我认为:paras=sorted(paras) 在我看来,但发生的情况是我丢失了单词字典的数据结构。 word['type']='verb', word['special']='true' 我得到错误:“'list' object has no attribute 'keys'”
-
不,你没有得到一个“松散的结构”,你从字典中得到一个排序的键/值元组列表,然后你可以循环。你应该合理地(根据我的例子)在循环中使用
sorted();for k,v in sorted(paras):或类似的。此外,您完全跳过了代码的相关部分,即循环。
标签: python sorting dictionary