1

Say I have a dict:

d = {
    'eggs': 4,
    'cheese': 6,
    'coconuts': 8,
}

Is is possible to loop over the dictionary, creating variables named after the keys, assigning them the corresponding value?

eggs = 4
cheese = 6
coconuts = 8

Or maybe inside an object?

self.eggs = 4
self.cheese = 6
self.coconuts = 8

Is this possible?

3
  • 1
    If you already have them in a dict, why do you need them as variables? Just curious. Commented Jul 18, 2011 at 15:47
  • 1
    Possible? Yes. Advisable, acceptable, a good idea? Most propably no. Why would you want/need this? Commented Jul 18, 2011 at 15:48
  • Explaining "why" is material for a separate question. Later today, possibly. So for now, please slap a huge "not-advisable" sticker on it, if you must, but I'd still like to know how. Commented Jul 18, 2011 at 15:51

3 Answers 3

6
>>> d = {
...     'eggs': 4,
...     'cheese': 6,
...     'coconuts': 8,
... }
>>> globals().update(d)
>>> eggs
4
>>> cheese
6
>>> coconuts
8
>>> d
{'cheese': 6, 'eggs': 4, 'coconuts': 8}

But for classes, it is easier(safer), just use:

for item, value in d.items():
     setattr(some_object, item, value) #or self.setattr(item, value)
Sign up to request clarification or add additional context in comments.

1 Comment

I used this method for a script in my job. This perl guy saw it and said "now I know you can write one line of python, and screw up the readability of an entire module"
4

You could use Alex Martelli's Bunch class:

>>> class Bunch(object):
...     def __init__(self, **kwds):
...         self.__dict__.update(kwds)
...
>>> d = {
...     'eggs': 4,
...     'cheese': 6,
...     'coconuts': 8,
... }
>>> b = Bunch(**d)
>>> b.eggs
4

Comments

2

Use setattr:

d = {
    'eggs': 4,
    'cheese': 6,
    'coconuts': 8,
}

class Food: pass

food = Food()

for item in d.iteritems():
    setattr(food, *item)

print(food.eggs, food.cheese, food.coconuts)

1 Comment

setattr(food, *item) was interesting (+1).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.