【问题标题】:In python, how to order a dict with unicode content?在 python 中,如何订购带有 unicode 内容的字典?
【发布时间】:2019-09-09 15:27:41
【问题描述】:

我有以下字典:

<type 'dict'>
{u'010-010': u'010-010_comp_v000', u'012-010': u'012-010_comp_v002', u'007-010': u'007-010_comp_v000', u'006-010': u'006-010_comp_v009', u'005-010': u'005-010_comp_v002'}

我想用钥匙订购。但是使用 Collections 和 OrderedDict,我无法让它工作。

OrderedDict([(u'010-010', u'010-010_comp_v000'), (u'012-010', u'012-010_comp_v002'), (u'007-010', u'007-010_comp_v000'), (u'006-010', u'006-010_comp_v009'), (u'005-010', u'005-010_comp_v002')])

我假设它与 unicode 相关联?有没有解决方案来纠正这个问题而不必重写字典?这是另一个软件的输出,所以我不能轻易改变类型。

想要的输出是:'005-010'... '006-010'... '007-010'...

【问题讨论】:

    标签: python dictionary python-unicode ordereddictionary


    【解决方案1】:

    OrderDicts 保留插入顺序 - 他们不会为您排序项目。您需要自己对它们进行排序:

    d = {u'010-010': u'010-010_comp_v000', u'012-010': u'012-010_comp_v002', u'007-010': u'007-010_comp_v000', u'006-010': u'006-010_comp_v009', u'005-010': u'005-010_comp_v002'}
    o = OrderedDict((k, v) for k, v in sorted(d.items()))
    print(o)
    

    【讨论】:

    • @ScottHunter:关键是要保留插入顺序。 (u 前缀表明这几乎肯定是 Python 版本,而 dict 没有这样做。)
    • OP 说“我想用钥匙订购”,所以,也许吧。我们会看看这是否是他们正在寻找的......
    • 这正是我正在搜索的内容。谢谢!
    猜你喜欢
    • 2013-06-10
    • 2012-05-10
    • 2010-10-26
    • 2023-01-30
    • 2021-11-02
    • 2022-11-13
    • 2011-11-07
    • 2011-05-15
    • 1970-01-01
    相关资源
    最近更新 更多