Q:

python sort 2D dictionary by index

I have a 2D dictionary as follows
    dict =  {'182.12.17.50': {'185.23.15.69': 30, '175.12.13.14': 14}, '182.15.12.30': {'175.12.13.15': 10, '145.33.34.56': 230}}

I want to sort that based on the value such that the out put looks like 
  [{IP1: '182.15.12.30', IP2: '175.12.13.15', val:10}, {IP1: '182.12.17.50', IP2: '175.12.13.14', val:14}, ...]

I am a newbie in python. I have written an ugly code for that. Is there any nice way to implement that?
Thanks,

A:

You can use a generator expression and the built-in sorted:
sorted(({'IP1': ip1, 'IP2': k, 'val':v}
           for ip1,subdct in dct.items()
           for k,v in subdct.items()),
       key=lambda newd: newd['val'])

By the way, it's a bad idea to use dict as the name of a variable, as doing so overshadows the built-in dict. Therefore, I renamed the variable to dct.

