Newbie question on dictionary!!!

Tom B. sbabbitt at
Fri Aug 27 03:43:39 CEST 2004

"Balaji" <balaji at> wrote in message
news:494182a9.0408261150.a4c767f at
> Hello everybody...
> I want to ask a simple question.
> Suppose I have an list say g=['a','b','c','d']
> and I have an dictionary say k={'b':20,'a':10}
> Now I want to sort this dictionary on the basis of the list and if it
> doesnt find any of the element in the list then I wud like to replace
> it with zero..
> so I would like to modify k into {'a':10,'b':20,'c':0,'d':0}
> I have tried all the built in associated with dict and lists but was
> not able to come up with an solution...
> Can anyone help...

Dictionaries are not sortable but you can easily access the values in an
sorted order,

list = ['a','b','d']
dict = {'a':123,'c':456,'b':789}
newdict = {}
l = dict.keys() + list
for i in l:
    if dict.has_key(i):
        newdict[i] = dict[i]
        newdict[i] = 0
dict = newdict

That should do it,


     print dict[i]


More information about the Python-list mailing list