Finding the same second elements in nested lists - recursive function
<p>I have nested lists looks like this;</p>

<pre><code>[['CELTIC AMBASSASDOR', 'Warrenpoint'],['HAV SNAPPER', 'Silloth'],['BONAY', 'Antwerp'],['NINA', 'Antwerp'],['FRI SKIEN', 'Warrenpoint']]
</code></pre>

<p>and goes on. How can I find the lists that have same second elements, for example</p>

<pre><code>['CELTIC AMBASSASDOR', 'Warrenpoint']
['FRI SKIEN', 'Warrenpoint']

['BONAY', 'Antwerp']
['NINA', 'Antwerp']
</code></pre>

<p>The list is too long (I'm reading it from a .csv file) and I can't determine to search which thing exactly (eg: I can't search for 'Antwerp' to find all Antwerps because I don't know all of the texts in csv file), so I thought I need a recursive function that will search until find the all nested lists seperated by second items. Couldn't figure out how to make the recursive function, if anyone has a better solution, much appreciated.</p>

<p>There's no need to use recursion here. Create a dictionary with a key of the second element and values of the whole sublist, then create a result that only includes the matches you're interested in:</p>

<pre><code>import collections
l = [['CELTIC AMBASSASDOR', 'Warrenpoint'],['HAV SNAPPER', 'Silloth'],['BONAY', 'Antwerp'],['NINA', 'Antwerp'],['FRI SKIEN', 'Warrenpoint']]
d = collections.defaultdict(list)
for item in l:
    d[item[1]].append(item)

result = dict(item for item in d.items() if len(d[item[0]]) &gt; 1)
</code></pre>

<p>Result:</p>

<pre><code>&gt;&gt;&gt; import pprint
&gt;&gt;&gt; pprint.pprint(result)
{'Antwerp': [['BONAY', 'Antwerp'], ['NINA', 'Antwerp']],
 'Warrenpoint': [['CELTIC AMBASSASDOR', 'Warrenpoint'],
                 ['FRI SKIEN', 'Warrenpoint']]}
</code></pre>

python list recursion python-3.4 nested-lists