[Tutor] How to load a dict into a dict subclass?

Modulok modulok at gmail.com
Tue Oct 27 13:25:14 CET 2009


List,

I'm new to the list, (somewhat new to python too). My code feels
hacky. I'd like to know if there is a more eloquent way (more below).
If not, a general thumbs up from more experienced programmers would be
great!

Assume I have a dict, 'foo'. I also have my own class, 'Bar', which
subclasses (i.e. is a derived class) of a dict. How do I eloquently
get foo into an instace of Bar? Example:


### BEGIN CODE:
class Bar(dict):
   pass # Act like a dict for now.

foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return value.
myvar = Bar()
# The hacky feeling part:
for k,v in foo.items(): myvar[k] = v

### END CODE

Obviously I can put the dict into an instance variable, but then
methods like 'keys()' and such won't work. If that makes any sense...

Thanks guys!
-Modulok-


More information about the Tutor mailing list