How to transform content from a dictionary file into Python?

1

Well, I have a file and I'm getting the contents of it and adding it to a variable. The contents of the file and the value of the variable are like this:

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

I would like to take this content from the variable and transform it into a dictionary in Python (3), like this:

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

Can anyone tell me how I can do it?

Thank you.

    
asked by anonymous 11.12.2018 / 05:03

3 answers

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"'}
    
11.12.2018 / 10:01
3

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

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

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

import configparser

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

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

See working at Repl.it

The output would be:

{
    'name': 'Maquina01', 
    'id': '"MAQ 15478"', 
    'version': '08'
}
    
11.12.2018 / 12:23
0

Using regular expressions (import re):

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

print(dict(re.findall(r'(\w+)=(.*)',v)))
    
12.12.2018 / 18:14