Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dictionary entries into variables

Is there a Pythonic way to assign the values of a dictionary to its keys, in order to convert the dictionary entries into variables? I tried this out:

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

I am certain that the key-value pairs are correct because they were previously defined as variables by me before. I then stored these variables in a dictionary (as key-value pairs) and would like to reuse them in a different function. I could just define them all over again in the new function, but because I may have a dictionary with about 20 entries, I thought there may be a more efficient way of doing this.

like image 815
HappyPy Avatar asked Aug 06 '13 21:08

HappyPy


People also ask

Can a dictionary value be a variable?

Variables can't be dict values. Dict values are always objects, not variables; your numbers dict's values are whatever objects __first , __second , __third , and __fourth referred to at the time the dict was created. The values will never update on the dictionary unless you do it manually. when they change..

Can a Python dictionary value be a variable?

You can assign a dictionary value to a variable in Python using the access operator [].

How do you turn a dictionary into a value list?

To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.

How do you convert a dictionary value to an array?

To convert a dictionary to an array in Python, use the numpy. array() method, and pass the dictionary object to the np. array() method as an argument and it returns the array.


1 Answers

You can do it in a single line with:

>>> d = {'a': 1, 'b': 2} >>> locals().update(d) >>> a 1 

However, you should be careful with how Python may optimize locals/globals access when using this trick.

Note

I think editing locals() like that is generally a bad idea. If you think globals() is a better alternative, think it twice! :-D

Instead, I would rather always use a namespace.

With Python 3 you can:

>>> from types import SimpleNamespace     >>> d = {'a': 1, 'b': 2} >>> n = SimpleNamespace(**d) >>> n.a 1 

If you are stuck with Python 2 or if you need to use some features missing in types.SimpleNamespace, you can also:

>>> from argparse import Namespace     >>> d = {'a': 1, 'b': 2} >>> n = Namespace(**d) >>> n.a 1 

If you are not expecting to modify your data, you may as well consider using collections.namedtuple, also available in Python 3.

like image 71
Peque Avatar answered Oct 20 '22 01:10

Peque