Python How can i read text file like dictionary
<p>I hava a text file like this :</p>

<pre><code>"imei": "123456789",
"sim_no": "+90 xxx xxx xx xx",
"device_type": "standart",
"hw_version": "1.01",
"sw_version": "1.02"
</code></pre>

<p>and i want read this file like dictionary. I mean, when i write imei it should give me 123456789. I'm creating free dictionary and i'm reading this file but its reading like string.</p>

<pre><code>file=open("test.txt","r")

buffer={}
print(type(buffer))
buffer=file.read()
print(type(buffer))

&lt;class 'dict'&gt;
&lt;class 'str'&gt; 
</code></pre>

<p>EDIT : Problem is solved.</p>

<pre><code>import json

with open("test.txt") as f:
    mydict = json.loads('{{ {} }}'.format(f.read()))
</code></pre>

<p>I tried to come up with a more elegant solution that doesn't use regular expressions, but everything I came up with is far more verbose, so try this:</p>

<pre><code>import re

d = {}
with open('test.txt') as f:
    for line in f:
        k, v = re.findall(r'"(.+?)"', line)
        d[k] = v

print(d)
</code></pre>

<p><code>re.findall(r'\"(.+?)\"', line)</code> will return all the matches where text is within quotes on each line, and assign the first match to <code>k</code> and the second to <code>v</code>. These are then used as keys and values in a dictionary <code>d</code>. Assuming that the format of your text file is constant, this should give you the result you are looking for.</p>

<p>Note that the order of the dictionary will likely be different than your text file, but that shouldn't matter since it is a dictionary.</p>

python python-3.x