Converting list of list to dictionary
<p>I have the following list of list:</p>

<pre><code>[[u'3', u'4'], [u'4', u'5'], [u'7', u'8'], [u'1', u'2'], [u'2', u'3'], [u'6', u'7'], [u'5', u'6']]
</code></pre>

<p>I want to obtain:</p>

<pre><code>{3:'4', 4:'5', 7:'8', 1:'2', 2:'3', 6:'7', 5:'6'}
</code></pre>

<p>List could be long, so it needs to be more efficient as possible.</p>

<p>The first element of each "pair" <code>[[first, second], ...]</code> is unique, so we can make a dictionary from it.</p>

<p>I tried with the following, but I think it will be slow:</p>

<pre><code>def getdict(l):
    result = {}
    for e in l:
        result[int(e[0])] = e[1]
    return result
</code></pre>

<p>You can use a <em>dictionary comprehension</em>:</p>

<pre><code>&gt;&gt;&gt; l = [[u'3', u'4'], [u'4', u'5'], [u'7', u'8'], [u'1', u'2'], [u'2', u'3'], [u'6', u'7'], [u'5', u'6']]
&gt;&gt;&gt; {int(key): value for key, value in l}
{1: u'2', 2: u'3', 3: u'4', 4: u'5', 5: u'6', 6: u'7', 7: u'8'}
</code></pre>

<p>Note that you would "lose" duplicates like in the @Kevin's example:</p>

<pre><code>&gt;&gt;&gt; l = [['1', '2'], ['1', '3']]
&gt;&gt;&gt; {int(key): value for key, value in l}
{1: '3'}
</code></pre>

python algorithm list dictionary