Python: Use specific parts of a string (that looks like a list)
<p>I have a text file (file.txt):</p>

<pre><code>(A-&gt;[a:5,a:5,a:5,b:50,c:10,c:10])
(B-&gt;[e:120,g:50])
(C-&gt;[a:5,f:20])
</code></pre>

<p>and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:</p>

<pre><code>totalValue = 20 # of 'a'
#OR
totalValue = 50 # of 'b'
#OR
totalValue = 20 # of 'c'
</code></pre>

<p>Note: text file is obviously not a list, even though it looks like it.</p>

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

while True:
    theline = myFile.readline()
    if "a" in theline:     #Just used 'a' here as an example.
        for char in theline:
            ...        

myFile.close()
</code></pre>

<p>That's roughly the code I have to read the file and check each line for 'a' (for example).</p>

<p>Thank you.</p>

<p>If I may suggest a somehow more compact solution that sums up every "key" in the text file and outputs a dictionary:</p>

<pre><code>import re
from collections import defaultdict

with open('a.txt') as f:
    lines = f.read()

tups = re.findall(r'(\w+):(\d+)', lines)
print(tups)
# tups is a list of tuples in the form (key, value), ie [('a': '5'), ...]

sums = defaultdict(int)
for tup in tups:
    sums[tup[0]] += int(tup[1])

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

<p>Will output:</p>

<pre><code>[('a', '5'), ('a', '5'), ('a', '5'), ('b', '50'), ('c', '10'), ('c', '10'), ('e', '120'), ('g', '50'), ('a', '5'), ('f', '20')]
defaultdict(&lt;class 'int'&gt;, {'f': 20, 'b': 50, 'e': 120, 'a': 20, 'c': 20, 'g': 50})
</code></pre>

<p>And more specifically:</p>

<pre><code>print(sums['a'])
&gt;&gt; 20
print(sums['b'])
&gt;&gt; 50
</code></pre>

python string file python-3.x