I want to sort this dictionary through its keys.I am adding two lists into one dictionary...

list1=[]
list2=[]
dict1={}
dict2={}
n=input("Enter the number of contacts : ")
for i in range(0,n):
    name1=raw_input("Enter your name: ")
    num=input("Enter your phone number: ")
    list1.extend([name1])
    list2.extend([num])
    dict1=dict(zip(list1,list2))#to convert two list into dictionary

keys=dict1.keys()
keys.sort()
for i in keys:
    dict2[i]=dict1[i]
print dict2

The keys in a Python dictionary are in hash order for fast look-up. You can not maintain alphanumeric order unless you use an OrderedDict object, new in Python27 and higher.

There is no reason to use a list, or if you do, don't create a new dictionary on every pass through the loop.

dict1={}

n=input("Enter the number of contacts : ")
for i in range(0,n):
    name1=raw_input("Enter your name: ")
    num=input("Enter your phone number: ")
    if name not in dict1:
        dict1[name] = num 
    else:
        print name, "already on file...NOT added"

keys=dict1.keys()
keys.sort()
for k in keys:          ## in name order
    print dict1[k], k

Edited 5 Years Ago by woooee: n/a

woooee's code brought name error on name1, so here running slightly simplified and only raw_input using version:

dict1={}

for i in range(int(raw_input("Enter the number of contacts : "))):
    name=raw_input("Enter your name: ")
    num=raw_input("Enter your phone number: ")
    if name not in dict1:
        dict1[name] = num 
    else:
        print name, "already on file...NOT added"

for k in sorted(dict1):          ## in name order
    print  k, dict1[k]

Edited 5 Years Ago by pyTony: n/a

This article has been dead for over six months. Start a new discussion instead.