Newbie question on dictionary!!!

Jeff Lindholm jeff_news at
Thu Aug 26 22:38:22 CEST 2004

> 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...

Here is a simple thing I was playing with today, that does some of what you 
want. You could use it for a simple starting point.

def countletters(s):
    ret = {}
    for c in s:
        ret[c] = ret.get(c, 0) + 1
    return ret

if __name__ == "__main__":
    #ret = countletters("this is only a test of the emergency broadcast 
system, had this been an actual emergency you would have been told where to 
tune your radio")
    ret = countletters(['a','b','b','c'])
    li = ret.items()
    print "\n\n",li,"\n\n" 

More information about the Python-list mailing list