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>you can use <code>collections.defaultdict</code>:</p>

<p>you 1st answer</p>

<pre><code>import collections.defaultdict
my_dict = cillections.defaultdict(list)
with open('your_file') as f:
    for line in f:
         line = line.strip().split()
         my_dict[line[0]].append(line[1])

print my_dict
</code></pre>

<p>Taking above example, you might able to solve 2nd question.</p>

python