如何在Python中按键对字典排序

如何在Python中按键对字典排序,python,sorting,dictionary,Python,Sorting,Dictionary,有人能告诉我如何分类吗: {'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']} 进入 ?? 谢谢 更新1,代码示例: 所以我在学语言学。一篇文章被分解为存储在数据库中的单词,这些单词具有各种属性,包括段落ID和句子ID。任务:尝试重建原始文本 从数据库中获取500个连续单词 words = Words.objects.all()[w

有人能告诉我如何分类吗:

{'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}
进入

?? 谢谢

更新1,代码示例:

所以我在学语言学。一篇文章被分解为存储在数据库中的单词,这些单词具有各种属性,包括段落ID和句子ID。任务:尝试重建原始文本

从数据库中获取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]=[]
words=words.objects.all()[wordId:wordId+500]
#我首先创建段落,然后在django模板中循环,
#在每一段中都有一个单词列表(还有字典)。
#所以我试图得到一个字典,它的值是字典列表。
#“pp”是一个很长的命名变量的缩写。
第{}段
段落高=段落低=单词[0]。属于段落
对于w,大写:
最后一个字=w
pp=w.属于第段
如果pp>段落高:
para_high=pp
如果pp
然而,在这一点上,如果我尝试循环dict并重新构建文本,一些后面的id段落会出现在前面的段落之前,而这根本不起作用

更新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 %}
{%k,v在wording.iteritems()%}
{%if v[0]=='break%}

{%else%} {%for v%}{%if-word.special==0%}{%endif%}{{word.word}}{%endfor%} {%endif%} {%endfor%}
Dicts没有订单

您可以调用sorted,但这只会提供键的排序列表:

>>> sorted(d)
['a', 'b', 'c', 'd']
您可以将其视为一个iterable并对键值元组进行排序,但是您只得到一个元组列表,这与dict不同

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

如果您使用Python 2.7或更新器,您也可以考虑使用.< /P> dict子类,用于记住添加的订单条目

例如:

>>> d = collections.OrderedDict(sorted(d.items()))
>>> for k, v in d.items():
>>>     print k, v
>>> from sortedcontainers import SortedDict
>>> d = {'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}
>>> s = SortedDict(**d)
>>> s.keys()
SortedSet(['a', 'b', 'c', 'd'])
a[1,2,3] b['blah','bhasdf','asdf'] c[‘一’、‘二’] d['asdf','wer','asdf','zxcv']
正如另一个答案所提到的,字典键的顺序是任意的,你不应该依赖它


如果您使用的是Python 2.7或3.1或更高版本,请尝试使用
collections.OrderedDict
(;;另请参阅)。文档中有一个链接指向在早期Python版本上工作的。正确的答案是,如果您希望字典中的项按排序顺序排列,则应使用排序()在字典上循环时的函数:

>>> d = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5}

或类似的

提到的OrderedDict适用于具有顺序的词典。顺序与排序不同。您可以创建已排序的OrderedDict,是的,但只要添加一个新键,它就不再排序了。因此您需要使用sorted()无论如何,在每次使用前或每次操作后对其进行排序。因此,OrderedDict只比普通字典更慢、更占用内存,而不添加任何您需要的内容

OrderedDict不适用于已排序的词典,但适用于项目具有某种排序而不是排序的词典。例如,如果您希望按照添加的顺序显示内容,或者如果您希望用户能够任意排序内容

更新:进一步解释

为什么OrderedICT不是解决方案?因为OrderedICT是有序的而不是排序的

以标准词典为例:

>>> d = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5}
它没有排序,正如我们在下面看到的,“c”将出现在“b”之前。它也没有顺序,如果我们添加新的东西,它看起来像是随机顺序:

>>> d['g'] = 6
>>> d['i'] = 8
>>> d
{'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8}
好的,那么让我们使用OrderedDict:

>>> o = OrderedDict(sorted({'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5}.items()))
>>> o
OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5)])
啊哈!分类了!那么分类了吗?没有

>>> o['i'] = 8
>>> o['g'] = 6
>>> o
OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('i', 8), ('g', 6)])
什么?g在i之后结束?!为什么!?因为OrderedICT没有排序,它是有序的。它记住你添加东西的顺序。而不是排序。这意味着每次使用它时,你都需要先对它排序。OrderedICT只会在你不向它添加键的情况下保持排序。但是如果你不打算修改它,那么你就不必修改它你也可以有一个列表。这是你从排序()中得到的:

但这在标准词典中同样有效,因此OrderedDictionary没有帮助:

>>> sorted(d.items())
[('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('i', 8)]
结论 因此,每次您希望以排序方式循环字典时,都需要执行以下操作:

>>> for k in sorted(o):
...   print k, o[k]
... 
a 0
b 1
c 2
d 3
e 4
f 5
g 6
i 8

不管你使用什么字典,OrderedDict都不会真正帮助你,因为它不关心排序,只关心你添加内容的顺序。

还值得一提的是heapq中最大的例程。它会排序并返回前N项。根据实际需要,如果你使用关键参数。我主要提到这一点,因为我几天前发现了它,它完全符合我的要求。请参阅和。

我将在其他人已经解释的基础上再加上我的一分钱。在一个特定情况下,我碰巧遇到了完全相同的问题。我需要字典的输出始终保持不变,以编写稳定的单元测试

如果碰巧是您想要实现的,或者是其他与输出相关的任务,那么您根本不需要对任何内容进行排序,只需使用
pprint
module,在其他功能中,它将按键对字典进行排序

>>> d = {'a':1, 'b':2, 'c':3}
>>> print d
{'a': 1, 'c': 3, 'b': 2}

>>> from pprint import pprint
>>> pprint(d)
{'a': 1, 'b': 2, 'c': 3}

值得注意的是,Python有许多字典实现,它们按顺序排序。

>>> sorted(d.items())
[('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('i', 8)]
>>> for k in sorted(o):
...   print k, o[k]
... 
a 0
b 1
c 2
d 3
e 4
f 5
g 6
i 8
>>> d = {'a':1, 'b':2, 'c':3}
>>> print d
{'a': 1, 'c': 3, 'b': 2}

>>> from pprint import pprint
>>> pprint(d)
{'a': 1, 'b': 2, 'c': 3}
>>> from sortedcontainers import SortedDict
>>> d = {'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}
>>> s = SortedDict(**d)
>>> s.keys()
SortedSet(['a', 'b', 'c', 'd'])
def sortdict(dct):
    kys = dct.keys()
    kys.sort()
    from collections import OrderedDict
    d = OrderedDict()
    for x in kys: 
        for k, v in dct.iteritems():
            if (k == x):
                d[k] = v
    return d
from sdict import sortdict
import json
dct = {'sizes':[32,28,42], 'dog':'schnauser', 'cat':'siamese', 'bird':'falcon'}
dctx = sortdict(dct)
print json.dumps(dctx) 
$ python test.py
{"bird": "falcon", "cat": "siamese", "dog": "schnauser", "sizes": [32, 28, 42]}