You cannot sort a dict in place, because Python dicts are unordered. You have at least 2 alternatives :
Create a sorted list of tuples
You can use sorted
with a key=
argument. In this case, it would 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'])]
It returns a sorted list of tuples, which you can use to iterate and print the result :
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))
# UserID : 1. Username : Joe
# UserID : 2. Username : Toby
# UserID : 3. Username : Julie
# UserID : 4. Username : John
Create an OrderedDict
If you want to sort data
and keep the functionality of a dict
, you can create an 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]))
# OrderedDict([('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'])])
Note : For both examples, key=lambda x: x[1]
would also be enough.