In Python, how do I iterate over a dictionary in sorted key order?

后端 未结 10 993
有刺的猬
有刺的猬 2020-11-27 10:19

There\'s an existing function that ends in the following, where d is a dictionary:

return d.iteritems()

that returns an unsort

10条回答
  •  眼角桃花
    2020-11-27 11:02

    A dict's keys are stored in a hashtable so that is their 'natural order', i.e. psuedo-random. Any other ordering is a concept of the consumer of the dict.

    sorted() always returns a list, not a dict. If you pass it a dict.items() (which produces a list of tuples), it will return a list of tuples [(k1,v1), (k2,v2), ...] which can be used in a loop in a way very much like a dict, but it is not in anyway a dict!

    foo = {
        'a':    1,
        'b':    2,
        'c':    3,
        }
    
    print foo
    >>> {'a': 1, 'c': 3, 'b': 2}
    
    print foo.items()
    >>> [('a', 1), ('c', 3), ('b', 2)]
    
    print sorted(foo.items())
    >>> [('a', 1), ('b', 2), ('c', 3)]
    

    The following feels like a dict in a loop, but it's not, it's a list of tuples being unpacked into k,v:

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

    Roughly equivalent to:

    for k in sorted(foo.keys()):
        print k, foo[k]
    

提交回复
热议问题