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

Modulok modulok at gmail.com
Wed Oct 28 08:46:09 CET 2009


<snip>
...
>> 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
>>
> You can use the built-in function for dictionaries called update.  So
>
>  >>> class Bar(dict):
>  >>>     pass
>
>  >>> foo = {'a':100, 'b':200, 'c': 300}
>  >>> myvar = Bar()
>  >>> myvar.update(foo)
>  >>> myvar
> {'a': 100, 'c': 300, 'b': 200}
...
</snip>

Thanks guys!

Christian, that's just what I was looking for. Thank you!
-Modulok-


More information about the Tutor mailing list