Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert module to dict

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?

EDIT

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.

like image 466
blueFast Avatar asked Feb 24 '16 09:02

blueFast


People also ask

How do I turn a object into a dictionary in python?

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.

What is dict () function?

The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.

Is dict () a method in Python?

Python dict() MethodThe dict() method creates a dictionary object from the specified keys and values, or iterables of keys and values or mapping objects.

Can we convert list to dictionary in Python?

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.


1 Answers

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
like image 138
heykarimoff Avatar answered Sep 21 '22 19:09

heykarimoff