【问题标题】:How do you sort a dictionary by key, and return the entire dictionary with both key and value? [duplicate]如何按键对字典进行排序,并返回包含键和值的整个字典? [复制]
【发布时间】:2018-04-06 01:56:17
【问题描述】:

这是我所拥有的:

 dict = {'b':[456], 'a': [123]}

 sort_dict = sorted(dict.items(), key = str)
 return sort_dict

我的代码返回的内容:

[('a', [123]), ('b', [456])]

我需要它返回什么:

{'a':[123], 'b':[456]}

我知道我可以制作一个 for 循环或其他东西来制作一个新的 dict,但是还有另一种/更简单的方法可以做到这一点吗?谢谢!

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:
    from collections import OrderedDict
    
    >>> OrderedDict(sorted(d.items(), key=str))
    OrderedDict([('a', [123]), ('b', [456])])
    

    对于 Python 3.6+ 这已经足够了(阅读 cmets 了解更多详情):

    d = {'b':[456], 'a': [123]}
    
    >>> dict(sorted(d.items(), key=str))
    {'a': [123], 'b': [456]}
    

    不要将变量命名为 dictliststr 等,因为这些是 built-in functions 的名称。

    【讨论】:

    • 注意:此行为仅适用于 Python 3.6 及更高版本(以及it isn't actually guaranteed by the 3.6 spec,尽管它恰好适用于 CPython)。在 3.6 之前,dict 顺序与创建密钥的顺序几乎没有关系(对于 str 密钥,每次运行都不同)。
    猜你喜欢
    • 1970-01-01
    • 2013-03-14
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多