JSchwartz
JSchwartz

Reputation: 2724

Sort dictionary alphabetically when the key is a string (name)

First, I know there are a LOT of posts on dictionary sorting but I couldn't find one that was exactly for my case - and I am just not understanding the sorted(...lambda) stuff - so here goes.

Using Python 3.x I have a dictionary like this:

dictUsers[Name] = namedTuple(age, address, email, etc...)

So as an example my dictionary looks like

[John]="29, 121 bla, [email protected]"
[Jack]="32, 122 ble, [email protected]"
[Rudy]="42, 123 blj, [email protected]"

And right now for printing I do the following (where response is a dictionary):

for keys, values in response.items():
    print("Name= " + keys)
    print ("   Age= " + values.age)
    print ("   Address= " + values.address)
    print ("   Phone Number= " + values.phone)

And when the user asks to print out the database of users I want it to print in alphabetical order based on the "name" which is used as the KEY.

I got everything to work - but it isn't sorted - and before starting to sort it manually I thought maybe there was a built-in way to do it ...

Thanks,

Upvotes: 34

Views: 134263

Answers (7)

Mukund Biradar
Mukund Biradar

Reputation: 151

dict1={"d":1,"a":3,"z":0}

x=sorted(dict1.items())

print(x)

output

[('a', 3), ('d', 1), ('z', 0)]

Upvotes: 4

ciolo
ciolo

Reputation: 147

You can use OrderedDict with sorted:

from collections import OrderedDict

test_dict = {}

ordered_dict = OrderedDict(sorted(test_dict.items(), key=lambda t: t[0]))

Upvotes: 3

nvkr_
nvkr_

Reputation: 497

i would do it like:

sorted_dict = {key: value for key, value in sorted(unsorted_dict.items())}

Upvotes: 42

Gopinath S
Gopinath S

Reputation: 121

def sort_dict_by_key(unsorted_dict)  

    sorted_keys = sorted(unsorted_dict.keys(), key=lambda x:x.lower())

    sorted_dict= {}
    for key in sorted_keys:
        sorted_dict.update({key: unsorted_dict[key]})

    return sorted_dict

un_sorted_dict = {'Epsilon': 5, 'alpha': 1, 'Gamma': 3, 'beta': 2, 'delta': 4}
sorted_dict = sort_dict_by_key(un_sorted_dict)
print(sorted_dict) # {'alpha': 1, 'beta': 2, 'Epsilon': 5, 'Gamma': 3, 'delta': 4}

Upvotes: 0

Sirmione
Sirmione

Reputation: 311

dictio = { 'Epsilon':5, 'alpha':1, 'Gamma':3, 'beta':2, 'delta':4 }

sortedDict = dict( sorted(dictio.items(), key=lambda x: x[0].lower()) )

for k,v in sortedDict.items():
    print('{}:{}'.format(k,v))

output

 alpha:1
 beta:2
 delta:4
 Epsilon:5
 Gamma:3

Upvotes: 14

gosuto
gosuto

Reputation: 5741

Just to reiterate @hughdbrown's comment in a separate answer, because I missed it at first and believe it to be the true answer to this question:

You have a dictionary you want to sort alphabetically, say dictio:

dictio = {'Beta': 2, 'alpha': 1}

sorted() will alphabetically sort the keys for you into a list, given that you convert all keys to lowercase (otherwise uppercase entries will be sorted first, then all lowercase):

sortedkeys = sorted(dictio, key=str.lower)

By calling the original dictionary again using that list of sorted keys you then can output it alphabetically:

for i in sortedkeys:
    print dictio[i]

Upvotes: 2

sundar nataraj
sundar nataraj

Reputation: 8702

simple algorithm to sort dictonary keys in alphabetical order, First sort the keys using sorted

sortednames=sorted(dictUsers.keys(), key=lambda x:x.lower())

for each key name retreive the values from the dict

for i in sortednames:
   values=dictUsers[i]
   print("Name= " + i)
   print ("   Age= " + values.age)
   print ("   Address= " + values.address)
   print ("   Phone Number= " + values.phone)

Upvotes: 25

Related Questions