Import a file as a dict() in Python 3

python print dictionary
how to format each dictionary item as a text string in the input file
python dictionary keys list
converting text file to dictionary python
python dictionary values to list
load text file into dictionary python
python create dictionary from text file
python dict keys

I have a file I was playing around with to see if I can import it and convert it to a Python dictionary.

It is the default pyenv.cfg file in venv. It reads:

home = C:\Users\nope\AppData\Local\Continuum\anaconda3
include-system-site-packages = false
version = 3.6.4

I tried using:

with open(file, mode='r', encoding='utf-8') as f:
    new_f = f.read().replace('=', ':')
    d = dict(new_f)

This tells me I don't have enough arguments for dict(). It expects 2. I'm familiar with using dict(zip(list_1, list_2)) to create a dictionary. I'm not familiar with opening a file and creating one.

I'm looking for a very simply way to do this. I did some research with re and it isn't turning out. Withing the with block, I ran a = f.read().replace(' = ', '\',\'') which returns:

home','C:\Users\nope\AppData\Local\Continuum\anaconda3
include-system-site-packages','false
version','3.6.4

Now I need to add a ' at the beginning and end of each line. Then I think I can use f.readlines() to create a list I can slice into keys and values. I know how to do this with vim or sed in Linux, but I'm trying to stay within Python.

Please help. Thank you!

I can suggest you an alternative one-line style solution using dict comprehension:

with open('pyenv.cfg') as f:
    d = {k:v for line in f for k,v in [line.strip().split(' = ')]}

print(d)
# {'home': 'C:\\Users\\nope\\AppData\\Local\\Continuum\\anaconda3',
#  'include-system-site-packages': 'false',
#  'version': '3.6.4'}

6. Dictionaries, sets, files, and modules, Another way to create a dictionary is to provide a list of key-value pairs using The easiest and most powerful way to format a string in Python 3 is to use the Calls made to readline() after reaching the end of the file return an empty string ( '' ). We can now import both modules and access question and answer in each:. Assuming a following text file (dict.txt) is present. 1 aaa. 2 bbb. 3 ccc. Following Python code reads the file using open() function. Each line as string is split at space character.

I would suggest taking a look at the builtin configparser library which will return a dictionary like object.

Alternatively you can simply split the lines on =

my_dict = {}
for line in open(file_path).readlines():
    key, val = line.strip().split('=')  # Remove \n and split on =
    my_dict[key.strip()] = val.strip()  # Remove trailing leading spaces use
    # Note that vals will all be strings you may need to convert type for some

Python Dict and File | Python Education, Assuming a following text file (dict.txt) is present. 1 aaa 2 bbb 3 ccc. Following Python code reads the file using open() function. Each line as  In Python version 3.5 and earlier, the dictionary data type is unordered. However, in Python version 3.6 and later, the dictionary data type remains ordered. Regardless of whether the dictionary is ordered or not, the key-value pairs will remain intact, enabling us to access data based on their relational meaning.

Just treat it as normal data, don't try to convert it to python or you will end-up going down the horrible eval road.

d = {}
file = 'pyenv.cfg'

with open(file) as f:
    for line in f:
        k, v = line.rstrip().split(' = ')
        d[k] = v

import pprint
pprint.pprint(d)

Gives:

{'home': 'C:\\Users\\nope\\AppData\\Local\\Continuum\\anaconda3',
 'include-system-site-packages': 'false',
 'version': '3.6.4'}

How to create a Python dictionary from text file?, import json filename = 'commands.txt' commands = {} with When the with block is exited it will automatically call .close() on the file for us. Note that in Python 3 you can pass it as the named argument maxsplit . Given the following data in a text file the task is to convert it into a Python dict having the command names as the keys and the command descriptions as the values. We will start with some output: The code that generated it: The json module is only being used here as a way to pretty-print our dict.

Python: convert a text file into a dictionary, When the wordsegment module is imported these files are read from disk and used to construct a Python dict mapping word to count pairs. 1 loops, best of 3: 286 ms per loop as reader: lines = (line.split('\t') for line in reader) result = dict() for word, number in lines: result[word] = float(number). 1 loops  No longer available in Python 3. Gives the total length of the dictionary. This would be equal to the number of items in the dictionary. Produces a printable string representation of a dictionary. type (variable) Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

Python: Load Dict Fast from File, dictConfig() calls dictConfigClass passing the specified dictionary, and then calls the Reads the logging configuration from a configparser -format file. RotatingFileHandler formatter: precise filename: logconfig.log maxBytes: 1024 backupCount: 3 This is signalled by an absolute import path to the factory being made  After a brief introduction to file formats, we’ll go through how to open, read, and write a text file in Python 3. When you’re finished with this tutorial, you’ll be able to handle any text file in Python. Prerequisites. For this tutorial, you should have Python 3 installed as well as a local programming environment set up on your computer.

logging.config — Logging configuration, A JSON file can have the endpoints of all the lines in a model representing Use the import function to import the JSON module. import json. The JSON module is mainly used to convert the python dictionary above into a Not only can the json.​dumps() function convert a Python datastructure to a JSON  This script will take in an arguement (your csv file) as sys.argv and print out the translated list of dictionaries #!/usr/bin/env python import csv import sys import pprint # Function to convert a csv file to a list of dictionaries.

Comments
  • you are throwing text at the dict generator dict. It does not work like that.. print the new_f that you are passing and you will see. Being a file or not is not significant here.
  • It turns out new_f is a string and that doesn't work unless I pass another argument. Further down, I was able to get a list from readlines() but need to add a ' at the beginning and end of each line. Have any ideas for that or do you have a better idea for what I'm trying to do overall?
  • it is a string that looks like a dict. You have to split it into key,value pairs and feed those to the dict constructor.
  • Oh that's right split() does the job.
  • In your case, you need a add a dummy section header to satisfy the configparser requirement.
  • I would suggest not using the keyword file as a variable. There also might be problems if the number of spaces round = is not exactly 1 each side.
  • @SteveBarnes: file is not a keyword (see keyword.kwlist). It used to be an alias for open in the old python 2, but we have gone past that a long time ago. I tend to avoid it myself, but the OP used it.