6
\$\begingroup\$
dc = {line.split('=')[0]: line.split('=')[1] for line in txt}

Below avoids duplication but is even longer:

dc = {k: v for line in txt for k, v in
      zip(*map(lambda x: [x], line.split('=')))}

Any better way? Just without any imports.


Context: with open('config.txt', 'r') as f: txt = f.read().split('\n')

a=1
bc=sea
>>> {'a': '1', 'bc': 'sea'}  # desired output; values should be string
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Just FYI, Python has a built-in ConfigParser for parsing configration files in INI format, which requires a section header for each section. \$\endgroup\$
    – GZ0
    Commented Oct 11, 2020 at 9:38

3 Answers 3

6
\$\begingroup\$
dc = dict(line.split('=') for line in txt)
\$\endgroup\$
1
  • \$\begingroup\$ I knew Python had to have better - excellent. \$\endgroup\$ Commented Oct 10, 2020 at 13:11
3
\$\begingroup\$

This is one of the types of problems that the walrus operator := can handle:

dc = {(s := line.split('='))[0]: s[1] for line in txt}

Of course, in this case there's a much cleaner solution.

\$\endgroup\$
3
\$\begingroup\$
{k: v for line in txt for k, v in [line.split('=')]}

Advantage over superb rain's answer is ability to modify k and v if needed. Slight memory & speed advantage by avoiding allocation via a generator (credit @GZ0):

{k: v for k, v in (line.split('=') for line in txt)}
\$\endgroup\$
5
  • 1
    \$\begingroup\$ @Graipher That's the idea, line is split into a "left' and "right", key and value, so a 'trick' around duplicating line.split. \$\endgroup\$ Commented Oct 10, 2020 at 18:47
  • 1
    \$\begingroup\$ You could also write (line.split("="),) to avoid allocating a list. \$\endgroup\$ Commented Oct 10, 2020 at 22:51
  • 2
    \$\begingroup\$ @MateenUlhaq That creates a tuple, which in this case is not much different from a list. One approach to avoid allocating a new collection is this: {k: v for k, v in (line.split('=') for line in txt)} \$\endgroup\$
    – GZ0
    Commented Oct 11, 2020 at 7:19
  • \$\begingroup\$ @GZ0 Nice improvement - can post as answer if you wish, or I'll edit it into mine with credit. \$\endgroup\$ Commented Oct 11, 2020 at 10:46
  • \$\begingroup\$ @OverLordGoldDragon You can edit it into yours. \$\endgroup\$
    – GZ0
    Commented Oct 11, 2020 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.