Skip to content

Instantly share code, notes, and snippets.

@bodiam
Last active December 22, 2015 02:59
Show Gist options
  • Select an option

  • Save bodiam/6407555 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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
Copy Markdown
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