简体   繁体   中英

How to create a dictionary from OS environment variables?

There are environment variables set in the operating system (macos):

MYSQL_HOST="127.0.0.1"
MYSQL_DATABASE="invoice"
MYSQL_UID="dude"
MYSQL_PWD="pass1234"

I would like to build a list called db_config such that the end result will look like:

db_config = {'host':"127.0.0.1", 'database':"invoice", 'user':"dude",
             'password':"pass1234"}

(Note that the environment variable names differ from the keys in db_config . db_config will be used to pass database connection credentials, and the keys must be those listed in the above db_config .)

I can "manually" set db_config using:

db_config={'host':os.environ['MYSQL_HOST'], 'database':os.environ['MYSQL_DATABASE'],
           'user':os.environ['MYSQL_UID'], 'password':os.environ['MYSQL_PWD']}

...but it seems like there should be a cleaner more pythonic way of doing this, but I can't figure it out.

config = {
    'host': 'MYSQL_HOST',
    'database': 'MYSQL_DATABASE',
    'user': 'MYSQL_UID',
    'password': 'MYSQL_PWD'
}
db_config = {k: os.environ.get(v) for k, v in config.items()}

Depending on how you want to treat items that aren't in os.environ , you can use a conditional dict comprehension to ignore them.

db_config = {k: os.environ.get(v) for k, v in config.items()
             if v in os.environ}

You may wish to rename old_name and new_name in the code below; and if you are sure that the environment variables will be present or require them to be available for your code to work correctly, you can remove the if section of the dictionary comprehension shown below:

import os

transformations = (
    ('MYSQL_HOST', 'host'),
    ('MYSQL_DATABASE', 'database'),
    ('MYSQL_UID', 'user'),
    ('MYSQL_PWD', 'password')
)

db_config = {
    new_name: os.environ[old_name]
    for old_name, new_name in transformations
    if old_name in os.environ
}

all ENV variable related to MYSQL in one dict

import os

keys = dict(os.environ).keys()

dic = {}
for key in keys:
    if 'MYSQL_' in key:
        dic.update({key.split('MYSQL_')[1]:os.environ.get(key)})

print(dic)      

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM