-3

How can I create a new sorted dictionary? I tried 2 methods but both get errors:

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)

error:

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

error:

Traceback (most recent call last):
  dictionar3.update(sorted(k), v)
TypeError: update expected at most 1 argument, got 2
quamrana
  • 33,740
  • 12
  • 54
  • 68

1 Answers1

2

Use dict.items() to get a sequence of keys and values. Sort that, then convert it back to a dictionary.

dictionary2 = dict(sorted(dictionary1.items())
Barmar
  • 669,327
  • 51
  • 454
  • 560