-4

So say I have a .txt file called example.txt, for example:

key1 value1
key2 value2
key2 value3

I want to create a dictionary from this txt file. In this case I want it to be example_dict = {'key1':'value2', 'key2':'value2', 'key3':'value3'} All the items in the txt file are strings and have a newline before the next item. So far the only code I have is opening the file:

example_dict = {}
with open('example.txt', 'r') as fin:
    for line in fin:

I don't understand how to go about creating this dictionary from the txt file.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • if your keys and values at same place as you shown in example then you can try this different method with regex : https://pastebin.com/hp2wprAC – Aaditya Ura Sep 30 '17 at 21:02

1 Answers1

0

You can try this:

new_file = [i.strip('\n').split() for i in open('example.txt')]
final_dict = {a:b for a, b in new_file}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • why the downvote? – Ajax1234 Sep 30 '17 at 20:35
  • LGTM. Don't understand the downvote. – MMF Sep 30 '17 at 20:39
  • 1
    Python doesn't guarantee that your file will be closed right away if you use `open` in a list comprehension like this (it has to be garbage collected, [see here](https://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important)). So it is better practice to use a context manager (`with`). Further, you can use the `dict()` builtin instead of the comprehension. The downvote is for answering such a clear duplicate, and the answer's content itself. – miradulo Sep 30 '17 at 20:43