I would like to do the following (python3):
In module settings.py
:
message = 'Hello'
In module __main__.py
:
from . import settings
def dict_from_module(module):
...
return d
print(dict_from_module(settings))
Running this should produce:
{'message': 'hello'}
Is there a canonical way of converting a module to a dictionary?
Using vars(settings)
gives lots of internal information:
{
'__builtins__': {
...
},
'__cached__': 'xxx/__pycache__/settings.cpython-34.pyc',
'__doc__': None,
'__file__': 'xxx/settings.py',
'__loader__': <_frozen_importlib.SourceFileLoader object at 0x7f87fc192518>,
'__name__': 'xxx.settings',
'__package__': 'xxx',
'__spec__': ModuleSpec(...),
'message': 'bye'
}
Which I do not want / need. I can filter that out (by removing keys starting with __
), but I would like to avoid hacking around if there is an accepted way of doing this.
By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.
The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.
Python dict() MethodThe dict() method creates a dictionary object from the specified keys and values, or iterables of keys and values or mapping objects.
You can convert a Python list to a dictionary using the dict. fromkeys() method, a dictionary comprehension, or the zip() method. The zip() method is useful if you want to merge two lists into a dictionary.
Hope this helps!
def dict_from_module(module):
context = {}
for setting in dir(module):
# you can write your filter here
if setting.islower() and setting.isalpha():
context[setting] = getattr(module, setting)
return context
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With