How to turn content from a file into a dictionary in Python?

Asked

Viewed 665 times

1

Guys, I have a file and I’m taking the contents of it and adding it into a variable. The contents of the file and the value of the variable is like this:

NAME=Maquina01
ID="MAQ 15478"
version=08

I’d like to take this variable content and turn it into a dictionary in Python(3), like this:

{'NAME':'Maquina01','ID':'MAQ 15478', 'version': 08}

Could someone tell me how I can do it?

Thank you.

  • Module configparser is native to Python and can handle INI files.

3 answers

3

If your file is in INI format, having a properly defined header:

[config]
NAME=Maquina01
ID="MAQ 15478"
version=08

You can use the native module configparser from Python to interpret the file:

import configparser

config = configparser.ConfigParser()
config.read('data.ini')

print(dict(config['config']))

See working on Repl.it

The exit would be:

{
    'name': 'Maquina01', 
    'id': '"MAQ 15478"', 
    'version': '08'
}
  • Very good I have knowledge of this too, but it is not INI file no.

  • @Williamcanin and why is it not?

  • Pq was a file of shellscript, they were variables. I wanted to take this file of variables in shellscript and pass in variables to Python.

2


value = """
NAME=Maquina01
ID="MAQ 15478"
version=08
"""

dict([ i.split('=') for i in value.strip().split('\n')])
{'NAME': 'Maquina01', 'version': '08', 'ID': '"MAQ 15478"'}
  • That’s right. Thank you.

0

Using Regular Expressions (import re):

import re
v=open("f.ini").read()

print(dict(re.findall(r'(\w+)=(.*)',v)))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.