You cannot sort the dict in place because Python dicts is unordered. You have at least 2 options:
Create a sorted list of tuples
You can use sortedwith an argument key=. In this case, this will be the first element of the dict value:
sorted(data.items(), key= lambda x: x[1][0])
# [('Joe', [1, 'Joe', 'password', 'Joe@Email.com']), ('Toby', [2, 'Toby', 'password', 'Toby@Email.com']), ('Julie', [3, 'Julie', 'password', 'Julie@Email.com']), ('John', [4, 'John', 'password', 'John@Email.com'])]
, :
data = {
"Joe": [1, "Joe", "password", "Joe@Email.com"],
"Toby": [2, "Toby", "password", "Toby@Email.com"],
"John": [4, "John", "password", "John@Email.com"],
"Julie": [3, "Julie", "password", "Julie@Email.com"]
}
for name, lst in sorted(data.items(), key=lambda x: x[1][0]):
print("UserID : %d. Username : %s" % (lst[0], name))
data dict, OrderedDict:
from collections import OrderedDict
data = {
"Joe": [1, "Joe", "password", "Joe@Email.com"],
"Toby": [2, "Toby", "password", "Toby@Email.com"],
"John": [4, "John", "password", "John@Email.com"],
"Julie": [3, "Julie", "password", "Julie@Email.com"]
}
data = OrderedDict(sorted(data.items(), key=lambda x: x[1][0]))
. key=lambda x: x[1].