Create dict from list of strings

Viewed 63

Given a list of strings as follows...

environment_variables = ['PIP_INDEX_URL=http://pypi.example.com/simple', 'PATH=/etc/apt/sources.list', ...]

... what is the most straightforward way to generate a dict from it?

It should look like:

{"PIP_INDEX_URL": "http://pypi.example.com/simple", "PATH": "/etc/apt/sources.list", ...}
2 Answers

You can pass the split strings directly to the dict() constructor:

environment_variables = ['PIP_INDEX_URL=http://pypi.example.com/simple', 'PATH=/etc/apt/sources.list']

dict(s.split('=') for s in environment_variables)

Which will produce:

{
  'PIP_INDEX_URL': 'http://pypi.example.com/simple',
  'PATH': '/etc/apt/sources.list'
}
d = {}
for envvar in environment_variables:
    key, value = envvar.split('=')
    d[key] = value

You could use Python 3.8's new "walrus" operator here, but I don't think it gets any easier to read.

d = {v[0]: v[1] for envvar in environment_variables if (v := envvar.split('='))}
Related