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

后端 未结 10 985
有刺的猬
有刺的猬 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 10:43

    sorted returns a list, hence your error when you try to iterate over it, but because you can't order a dict you will have to deal with a list.

    I have no idea what the larger context of your code is, but you could try adding an iterator to the resulting list. like this maybe?:

    return iter(sorted(dict.iteritems()))
    

    of course you will be getting back tuples now because sorted turned your dict into a list of tuples

    ex: say your dict was: {'a':1,'c':3,'b':2} sorted turns it into a list:

    [('a',1),('b',2),('c',3)]
    

    so when you actually iterate over the list you get back (in this example) a tuple composed of a string and an integer, but at least you will be able to iterate over it.

提交回复
热议问题