sorting by dictionary value in array python
<p>Okay so I've been working on processing some annotated text output.  What I have so far is a dictionary with annotation as key and relations an array of elements:</p>

<pre><code>'Adenotonsillectomy': ['0', '18', '1869', '1716'],
 'OSAS': ['57', '61'],
 'apnea': ['41', '46'],
 'can': ['94', '97', '1796', '1746'],
 'deleterious': ['103', '114'],
 'effects': ['122', '129', '1806', '1752'],
 'for': ['19', '22'],
 'gain': ['82', '86', '1776', '1734'],
 'have': ['98', '102', ['1776 1786 1796 1806 1816'], '1702'],
 'health': ['115', '121'],
 'lead': ['67', '71', ['1869 1879 1889'], '1695'],
 'leading': ['135', '142', ['1842 1852'], '1709'],
 'may': ['63', '66', '1879', '1722'],
 'obesity': ['146', '153'],
 'obstructive': ['23', '34'],
 'sleep': ['35', '40'],
 'syndrome': ['47', '55'],
 'to': ['143', '145', '1852', '1770'],
 'weight': ['75', '81'],
 'when': ['130', '134', '1842', '1758'],
 'which': ['88', '93', '1786', '1740']}
</code></pre>

<p>What I want to do is sort this by the first element in the array and reorder the dict as:</p>

<pre><code>'Adenotonsillectomy': ['0', '18', '1869', '1716']
'for': ['19', '22'],
'obstructive': ['23', '34'],
'sleep': ['35', '40'],
'apnea': ['41', '46'],
etc...
</code></pre>

<p>right now I've tried to use operator to sort by value:</p>

<pre><code>sorted(dependency_dict.items(), key=lambda x: x[1][0])
</code></pre>

<p>However the output I'm getting is still incorrect:</p>

<pre><code>[('Adenotonsillectomy', ['0', '18', '1869', '1716']),
 ('deleterious', ['103', '114']),
 ('health', ['115', '121']),
 ('effects', ['122', '129', '1806', '1752']),
 ('when', ['130', '134', '1842', '1758']),
 ('leading', ['135', '142', ['1842 1852'], '1709']),
 ('to', ['143', '145', '1852', '1770']),
 ('obesity', ['146', '153']),
 ('for', ['19', '22']),
 ('obstructive', ['23', '34']),
 ('sleep', ['35', '40']),
 ('apnea', ['41', '46']),
 ('syndrome', ['47', '55']),
 ('OSAS', ['57', '61']),
 ('may', ['63', '66', '1879', '1722']),
 ('lead', ['67', '71', ['1869 1879 1889'], '1695']),
 ('weight', ['75', '81']),
 ('gain', ['82', '86', '1776', '1734']),
 ('which', ['88', '93', '1786', '1740']),
 ('can', ['94', '97', '1796', '1746']),
 ('have', ['98', '102', ['1776 1786 1796 1806 1816'], '1702'])]
</code></pre>

<p>I'm not sure whats going wrong.  Any help is appreciated.</p>

<p>The entries are sorted in alphabetical order. If you want to sort them on integer value, convert the value to int first:</p>

<pre><code>sorted(dependency_dict.items(), key=lambda x: int(x[1][0]))
</code></pre>

python arrays sorting dictionary