Newbie question on dictionary!!!

Russell Blau russblau at hotmail.com
Thu Aug 26 15:57:22 EDT 2004


"Balaji" <balaji at email.arizona.edu> wrote in message
news:494182a9.0408261150.a4c767f at posting.google.com...
> 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...

You can't sort a dictionary.  By definition, the keys of a dictionary are
not accessed in any particular order.  See footnote 3 in
http://www.python.org/doc/current/lib/typesmapping.html

You could turn your dictionary into a list with the desired qualities:

result = [(item, k.setdefault(item, 0)) for item in g]

which will have the side-effect of creating the new keys you wanted in k,
although not in sorted order.

-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.





More information about the Python-list mailing list