faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 10 people (60%) answered Yes
Recently 4 of 8 people (50%) answered Yes

Entry

Weak dictionary

Aug 9th, 2008 02:15
Sek Tea, Nathan Wallace, unknown unknown, Hans Nowak, Snippet 145, Python Snippet Support Team


"""
Packages: basic_datatypes.dictionaries
"""
# weakdict.py
# It is *very* easy to make a weak dictionary in Python... This is a simple
# example.
# HN, 23 Nov 98
from UserDict import UserDict
class WeakDict(UserDict):
    def __setitem__(self, name, value):
        self.data[name] = value
        if not value:
            del self.data[name]
if __name__ == "__main__":
    wd = WeakDict()
    wd['hans'] = 25
    wd['anjo'] = 22
    wd['mari'] = 35
    wd['fred'] = 33
    print wd
    wd['fred'] = None   # this deletes the 'fred' entry
    print wd
http://regalos-de-navidad.blogspot.com/
http://regalosdesanvalentin.blogspot.com/
http://ideas-para-regalar.blogspot.com/