python - 如何在 Python 中按键对字典进行排序

标签 python sorting dictionary

谁能告诉我如何排序:

{'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 %}

最佳答案

字典没有顺序。

你可以调用 sorted 但这只是给你一个排序的键列表:

>>> sorted(d)
['a', 'b', 'c', 'd']

您可以将其视为一个可迭代对象并对键值元组进行排序,但您得到的只是一个元组列表。这和 dict 不一样。

>>> sorted(d.items())
[
 ('a', [1, 2, 3]),
 ('b', ['blah', 'bhasdf', 'asdf']),
 ('c', ['one', 'two']),
 ('d', ['asdf', 'wer', 'asdf', 'zxcv'])
]

如果您使用的是 Python 2.7 或更新版本,您还可以考虑使用 OrderedDict .

dict subclass that remembers the order entries were added

例如:

>>> d = collections.OrderedDict(sorted(d.items()))
>>> for k, v in d.items():
>>>     print k, v
a [1, 2, 3]
b ['blah', 'bhasdf', 'asdf']
c ['one', 'two']
d ['asdf', 'wer', 'asdf', 'zxcv']

关于python - 如何在 Python 中按键对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4642501/

相关文章:

python - 读取 3.2 GB 文件时 Pandas/Python 内存峰值

python - Scrapy只返回第一个结果

vb.net - 在VB中将列表转换为字典

python - 在Python中按值对多个字典进行排序

JAVA字典作为参数

python - Matplotlib 未绘制整条线

python - 将 bash 环境变量发送回 python fabric

mysql - 按 "rep"订购帖子,但仅限 "one"天限制

c++ - x = malloc(n * sizeof (int));无法将 void 转换为 int

python - 在python中按多个条件排序