how do i skip part of each line while reading from file in python
<p>I am new to python and not able to figure out how do i accomplish this.</p>

<p>Suppose file.txt contains following</p>

<pre><code>iron man 1
iron woman 2
man ant 3
woman wonder 4
</code></pre>

<p>i want to read this file into dictionary in the below format</p>

<pre><code>dict = { 'iron' : ['man', 'woman'], 'man' : ['ant'], 'woman' : ['wonder'] } 
</code></pre>

<p>That is the last part in each line being omitted while writing to dictionary.</p>

<p>My second question is can i read this file to dictionary in a way such that</p>

<pre><code>dict2 = { 'iron' : [('man', '1'), ('woman', '2')], 'man' : [('ant', '3')], 'woman' : [('wonder', '4')] } .
</code></pre>

<p>That is key <em>iron</em> will have 2 values but these 2 values being individual tuple.</p>

<p>Second question is for implementation of uniform cost search so that i can access <em>iron</em> child <em>man</em> and <em>woman</em> and cost for these children being 1 and 2</p>

<p>Thank you in advance</p>

<p>For the first question, what you want to do is read each line, split it using white spaces and use a simple if rule to control how you add it to your dictionary:</p>

<pre><code>my_dict = {}
with open('file.txt', 'r') as f:
    content = f.read()

for line in content.split('\n'):
    item = line.split()
    if item[0] not in my_dict:
        my_dict[item[0]] = [item[1]]
    else:
        my_dict[item[0]].append(item[1])
</code></pre>

<p>The second question is pretty much the same, only with a slightly different assignment:</p>

<pre><code>my_dict2 = {}
for line in content.split('\n'):
    item = line.split()
    if item[0] not in my_dict:
        my_dict[item[0]] = [(item[1], item[2])]
    else:
        my_dict[item[0]].append((item[1], item[2]))        
</code></pre>

python