Skip to content

Instantly share code, notes, and snippets.

@bodiam
Last active December 22, 2015 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bodiam/6407555 to your computer and use it in GitHub Desktop.
Save bodiam/6407555 to your computer and use it in GitHub Desktop.
Transforming a dict to objects in Python
class Light:
def __init__(self, id, name):
self.id = id
self.name = name
response = {"1": {"name": "bedroom"}, "2": {"name": "kitchen"}}
lights = [Light(id, response[id]["name"]) for id in response]
for x in lights:
print('{} : {}'.format(x.id, x.name))
@russel
Copy link

russel commented Sep 2, 2013

I'd avoid use of the % operator and user the format method instead.

print('{} : {}'.format(x.id, x.name))

@bodiam
Copy link
Author

bodiam commented Sep 2, 2013

Changed, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment