Newbie question on dictionary!!!
Alex Martelli
aleaxit at yahoo.com
Thu Aug 26 17:01:48 EDT 2004
Balaji <balaji at email.arizona.edu> 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}
If you want to end up with a dictionary, the 'sorting' part is moot.
Dictionaries use hashing -- NO order whatever, thus sorting just can't
apply, can't have any sense nor meaning whatsoever in context... you
might as well talk of coloring or flavouring or housetraining a
dictionary as you might of sorting it.
You can build the dictionary you require (but it will have no ordering
whatsoever, being a dictionary) with
dict([ (x, k.get(x, 0)) for x in g ])
(in Python 2.4 you may fruitfully omit those brackets).
Alex
More information about the Python-list
mailing list