如何在Python中按键对词典进行排序

2024-05-16 00:14:15 发布

您现在位置:Python中文网/ 问答频道 /正文

有谁能告诉我怎么解决这个问题吗:

{'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,代码示例:

所以我在学语言学。一篇文章被分解成存储在数据库中的单词,这些单词具有各种属性,包括段落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]=[]

不过,在这一点上,如果我尝试循环dict并重新生成文本,那么后面的一些I d'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 %}

Tags: andthetoinforifelsepp
3条回答

值得注意的是,Python有许多字典实现,它们按顺序维护键。考虑一下sortedcontainers模块,它是纯Python和fast-as-C实现。这里有一个performance comparison与其他快速和功能完整的实现相互标杆。

例如:

>>> 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'])

您还可以用SortedDict完全替换dict的使用,因为它支持快速的get/set操作和按键对项进行排序的迭代。

听写没有命令。

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

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

您可以将其视为iterable并对键值元组进行排序,但是您只得到一个元组列表。那和口述不一样

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

如果您使用的是Python2.7或更新版本,也可以考虑使用^{}

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']

正确的答案是,如果希望字典中的项按排序顺序排列,则在循环字典时应使用sorted()函数

for k, v in sorted(d.items()):
    print k, ':', v

或者

for k in sorted(d):
   print d[k]

或类似的。

上面提到的OrderedDict是为有顺序的词典而写的。顺序和排序不一样。可以创建已排序的OrderedDict,是的,但只要添加新密钥,它就不再被排序。因此您无论如何都需要使用sorted()在每次使用之前或每次操作之后对其进行排序。因此,OrderedDict只比普通字典慢,内存密集,而不添加任何需要的内容。

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

更新:进一步说明

为什么OrderedDict不是解决方案?因为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)])

啊哈!整理好了!那么OrderedDict管用!?没有

>>> 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没有排序,所以它是有序的。它会记住你添加东西的顺序。不是分类。这意味着每次使用它时,都需要先对它进行排序。一个OrderedDict只会保持排序,只要你不添加密钥。但如果你不打算修改它,那么你就不需要口述,你也可以有一个清单。从sorted()中可以得到:

>>> sorted(o.items())
[('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('i', 8)]

但这对于标准字典也同样适用,因此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并不能真正帮助您,因为它不关心排序,只关心您添加内容的顺序。

相关问题 更多 >