6

What is a good way to copy a google app engine entity (in python) to a dictionary object? I'm using db.Expando objects. All properties are expando properties.

Thanks!

Chris Dutrow
  • 42,732
  • 59
  • 174
  • 243

5 Answers5

4

Having an entity called foo try with:

foo.__dict__
systempuntoout
  • 65,753
  • 43
  • 162
  • 239
Aater Suleman
  • 2,110
  • 15
  • 10
  • 1
    this solution gives you everything on the object, for Model objects, user the properties method and for Expando's use the dynamic_properties method – Tom Willis May 10 '11 at 21:16
  • @Tom Willis - I Believe the "properties" and "dynamic_properties" methods return just the keys, requiring an iteration to get everything copied. "dynamic_properties" is also a key in the __dict__ object though, so I believe you can do: foo.__dict__['dynamic_properties'] – Chris Dutrow May 10 '11 at 22:18
  • 4
    This is a bad idea - as @Tom says, it'll return all the members of the object, which is not the same as a dict of properties. – Nick Johnson May 16 '11 at 00:41
  • Correction, its: foo.__dict__['_dynamic_properties'] (added underscore) – Chris Dutrow May 19 '11 at 22:14
  • @Dutrow A better idea would be to use `properties` and `dynamic_properties` - you shouldn't rely on internal implementation details. – Nick Johnson May 22 '11 at 18:35
2

This should work

from google.appengine.ext import db
db.to_dict(entity)
shilpi
  • 21
  • 1
2

try this. Where "m" is the instance of the Expando you wish to turn into a dictionary.

dict([(x,getattr(m,x)) for x in m.dynamic_properties()])
Tom Willis
  • 5,138
  • 20
  • 34
0

The new version of the Google Cloud Python client library doesn't work quite so gracefully. So this is a quick fix.

your_dict = {x: entity[x] for x in entity.keys()}

Remember, the strings are passed in and returned as unicode, not basestring. ;)

Dovy
  • 1,210
  • 9
  • 18
-2

The accepted answer should be:

{}.update(entity}
Camille Tolsa
  • 230
  • 5
  • 12