-3

I need to order the dict by the value into another dict as below

dict_filtro = {"Conector 1":{"alasca":30,"USA":10,"Brasil":20},
                "Conector 4":{"alasca":60,"USA":60,"Brasil":10},
                "Conector 3":{"alasca":70,"USA":15,"Brasil":24},
                "Conector 2":{"alasca":10,"USA":19,"Brasil":6}}

dict_ordered  = ordered_dict_by_value(dict_filtro,["alasca"])
print(dict_ordered)

>>{"Conector 2":{"alasca":**10**,"USA":19,"Brasil":6}},
   "Conector 1":{"alasca":**30**,"USA":10,"Brasil":20},
   "Conector 4":{"alasca":**60**,"USA":60,"Brasil":10},
   "Conector 3":{"alasca":**70**,"USA":15,"Brasil":24}}

I already search for many solutions but never fit with my problem.

  • A dictionary in python does not have an ordering that you can control; the way it's implemented under the hood means it doesn't have one. https://docs.python.org/3/library/collections.html#collections.OrderedDict has a special version of a dictionary if you are really set on using one, but as Robby says, it's probably not your best bet. If I were you, I'd try and make a list of keys, like ["Conector 2", "Conector 1"...], and then you can use the dictionary to look up the values associated with those keys when you need them. – Kaia Aug 27 '20 at 21:28
  • dictionaries ARE ordered since python version 3.6. see: https://softwaremaniacs.org/blog/2020/02/05/dicts-ordered/ – bitranox Aug 27 '20 at 21:35
  • @bitranox In 3.6 it was only a CPython implementation detail (and not before 3.6). In 3.7 it became official. – superb rain Aug 27 '20 at 22:01

1 Answers1

0

You can get it done with Pandas:

import pandas as pd

dict_filtro = {"Conector 1":{"alasca":30,"USA":10,"Brasil":20},
            "Conector 4":{"alasca":60,"USA":60,"Brasil":10},
            "Conector 3":{"alasca":70,"USA":15,"Brasil":24},
            "Conector 2":{"alasca":10,"USA":19,"Brasil":6}}

df = pd.DataFrame(dict_filtro)

a = df.transpose()
b = a.sort_values(by='alasca')
c = b.transpose()

data_dict = c.to_dict() 

print(data_dict)
Seyi Daniel
  • 2,259
  • 2
  • 8
  • 18