How To Sort List Inside Dict In Python?
I am trying to sort list inside of dict alphabetically but not able to do it. My list is {'B' : ['x', 'z', 'k'], 'A' : ['a', 'c', 'b']} What I want to do is, {'A' : ['k', 'x', 'z'
Solution 1:
You aren't actually calling the sort
method. Just specifying sort
will return a reference to the sort
method, which isn't even assigned anywhere in your case. In order to actually call it, you should add parenthesis:
for x in ab:
ab[x].sort()
# Here ---^
Solution 2:
Not sure if you have a typo in your snippets, but here's one way to sort the values of a dictionary, where the values are lists:
>>> d1 = {"B" : ["x", "z", "k"], "A" : ["a", "c", "b"]}
>>> d2 = {x:sorted(d1[x]) for x in d1.keys()}
>>> d2
{'A': ['a', 'b', 'c'], 'B': ['k', 'x', 'z']}
Post a Comment for "How To Sort List Inside Dict In Python?"