Sort nested dictionaries and replace dictioary values with ordered numbers
<p>Not sure if my problem sound a bit tricky..my requirement is like this: I have three columns of data in txt file as below:</p>

<pre><code>col1,col2,col3/n
11,0.95,21/n
11,0.75,22/n
11,0.85,23/n
11,0.65,24/n
12,0.63,22/n
12,0.75,24/n
12,0.45,25/n
...
</code></pre>

<p>col1 can be viewed as dict keys which repeat for &lt;= 5 times, col3 can also viewed as nested dict keys with values in col2, i.e. each key in col1 has &lt;= 5 pairs of (col2: col3). </p>

<p>I would like to sort the nested dictionary by col2 and replace the col2 values with highest ranking, i.e.: I don't care about the values in col2, i only care about the ranking of col3 for each col1 value:</p>

<pre><code>col1,col2,col3
11,1,21/n
11,2,23/n
11,3,22/n
11,4,24/n
12,1,24/n
12,2,22/n
12,3,25/n
...
</code></pre>

<p>I tried turning the data into nested dictionaries like: </p>

<pre><code>{col1:{col3:col2}}
{11:{21:0.95,22:0.75,23:0.85,24:0.65},12:{22:0.63,24:0.75,25:0.45}}
</code></pre>

<p>I have searched around and found some solutions like sort nested dict etc., but I cannot replace the values with rankings either...can someone please help?</p>

<p>Your input not defined here, I assumed as a list of list like this.</p>

<pre><code>[['col1', 'col2', 'col3'],
 ['11', '0.95', '21'],
 ['11', '0.75', '22'],
 ['11', '0.85', '23'],
 ['11', '0.65', '24'],
 ['12', '0.63', '22'],
 ['12', '0.75', '24'],
 ['12', '0.45', '25']]
</code></pre>

<p>Then you can do like this,</p>

<pre><code>result = {}
for i in input_list:
    if i[0] in result:
        result[i[0]].update({i[2]:i[1]})
    else:
        result[i[0]] = {i[2]:i[1]}
</code></pre>

<p><strong>Result</strong></p>

<pre><code>{'11': {'21': '0.95', '22': '0.75', '23': '0.85', '24': '0.65'},
'12': {'22': '0.63', '24': '0.75', '25': '0.45'},
'col1': {'col3': 'col2'}}
</code></pre>

python sorting dictionary