Convert Dictionary Entries into Variables

Convert dictionary entries into variables

This was what I was looking for:

>>> d = {'a':1, 'b':2}
>>> for key,val in d.items():
exec(key + '=val')

Divide a dictionary into variables

Problem is that dicts are unordered, so you can't use simple unpacking of d.values(). You could of course first sort the dict by key, then unpack the values:

# Note: in python 3, items() functions as iteritems() did
# in older versions of Python; use it instead
ds = sorted(d.iteritems())
name0, name1, name2..., namen = [v[1] for v in ds]

You could also, at least within an object, do something like:

for k, v in dict.iteritems():
setattr(self, k, v)

Additionally, as I mentioned in the comment above, if you can get all your logic that needs your unpacked dictionary as variables in to a function, you could do:

def func(**kwargs):
# Do stuff with labeled args

func(**d)

Creating or assigning variables from a dictionary

OK php brothers so here is a bad news, python can't create variables from out of space... like php can: ${$var} . To use local() is a very bad idea, because you'll have tons of problems with debugging, and there some locals already defined in there.. so it's really bad thing to do...

You can't create this programmatically like php does. I think it's called non-explicity, and this is one python general: You ALWAYS know variable name. This kind of stuff just a suicide in some cases, you need to write by hand tons of vars... Mostly i was unhappy because of things like XML parsing, but it appears that there are method how to convert python dictionary into class, I was told about this yesterday but still haven't checked how it works ( something like here )

How can I assign the values from a dictionary? (Python)

You can call .values() on the dictionary and unpack them directly into the variables

a,b,g=(my_dict.values())

b
0.30069982893451086

However, it's important to know that in versions prior to 3.7, dictionary entries are not ordered, so you can't rely on this type of unpacking unless you're on a newer version

Convert dictionary entries into variables

This was what I was looking for:

>>> d = {'a':1, 'b':2}
>>> for key,val in d.items():
exec(key + '=val')

Elegant way to unpack limited dict values into local variables in Python

You can do something like

foo, bar = map(d.get, ('foo', 'bar'))

or

foo, bar = itemgetter('foo', 'bar')(d)

This may save some typing, but essentially is the same as what you are doing (which is a good thing).



Related Topics



Leave a reply



Submit