【发布时间】: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
- 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