【问题标题】:how can i sort a new dictionary python [duplicate]我如何对新字典python进行排序[重复]
【发布时间】:2021-11-29 06:22:38
【问题描述】:

如何创建新的排序字典?我尝试了 2 种方法,但都出现错误:

dictionar1 = {"nume":"Simion",
     "prenume":"Marian",
     "varsta":"25",
     "angajat":"true",
     "adresa":"Braila, str. Mihai Eminescu, nr. 25"
}
dictionar2 = {}
for k in sorted(dictionar1.keys()):
    dictionar2.update(k)
print(dictionar2)

错误:

dictionar2.update(k)
ValueError: dictionary update sequence element #0 has length 1; 2 is required
  1. dictionar3 = {} 对于 dictionar1.items() 中的 k、v: dictionar3.update(sorted(k), v)

错误:

Traceback (most recent call last):
  dictionar3.update(sorted(k), v)
TypeError: update expected at most 1 argument, got 2

【问题讨论】:

  • 值得注意的是,新字典并不能保证在添加新键后保持顺序

标签: python sorting dictionary key key-value


【解决方案1】:

使用dict.items() 获取一系列键和值。对其进行排序,然后将其转换回字典。

dictionary2 = dict(sorted(dictionary1.items())

【讨论】:

    猜你喜欢
    • 2015-12-26
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多