0

I'm making a Python(3) progam to read this text file:

firstval="myval"
secondval="myotherval"

and turn it into a dict.

I tried this:

lines = file.readlines().split("\n")
values = []

for line in lines:
    values.append(line.split("="))

to turn the file into a list

How do i turn this:

values = ["firstval", "myval", "secondval", "myotherval"]

into this:

values = {
    "firstval": "myval",
    "secondval": "myotherval"
}
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 1
    Why not do it in one step? Read a line with key=value, split at =, add key and value to dict. No need for intermediate list of lines. – duffymo Jun 11 '22 at 17:04
  • Welcome back to Stack Overflow. Do you know how to create an empty dict? Do you know how to assign a new key/value pair to a dict? If you replace the "create an empty list" and "append to a list" steps in the original code, does that solve the problem? Also, the code you show does not produce a "flat" list like the one you describe. `.append` given a list will append the list, as a single item, i.e. a nested list. – Karl Knechtel Jun 11 '22 at 17:06
  • To the OP: we can give you answers to this, but it's better if you learn to debug some issues yourself. You said you "tried" that code, when you tried it, what error did you get out? It's not realistic to come to Stack Overflow every time your program doesn't work; you'll never make progress if you don't learn to read error messages and fix what the problem is. You're asking how to turn a flat list into a dictionary, but that won't really help fix the code, because that's not the error. You need to debug the error that happens before you even get a flat list. – kerkeslager Jun 11 '22 at 17:13

1 Answers1

0

You can use dict() with zip():

dict(zip(values[::2], values[1::2]))

This outputs:

{'firstval': 'myval', 'secondval': 'myotherval'}
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33