Newbie question on dictionary!!!
Jeff Shannon
jeff at ccvcorp.com
Thu Aug 26 16:49:12 EDT 2004
Balaji wrote:
>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}
>
>
Dictionaries don't maintain any particular sort order. (Or,
technically, dictionaries are by definition sorted by the result of
hash(value), which may not bear any resemblance to the sort order of
value.) So, we can't get your dictionary sorted the way you want, but
we *can* fill in the undefined keys.
You want to use the dictionary method get(). It will return the value
of a key, or a specified default value if that key isn't found. You can
then assign the result of that back into the dictionary under the same key.
for key in g:
k[key] = k.get(key, 0)
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list