简体   繁体   中英

Order object by keys in dict

I have a python dict that looks like this:

country_info = {
    "population": {
        "usa": "328 millions",
        "brazil": "209 millions",       
        "france": "70 millions"
    },
    "capital": {
        "brazil": "Brasilia",
        "usa": "Washington",
        "france": "Paris"
    },
    "language": {
        "france": "French",
        "usa": "English",
        "brazil": "Portuguese"
    }
}

How can I order every object by keys to be the same? It doesnt really matter in which order, as long as they are the same. When I loop through the dict in my flask template, I want the country_info dict to contain the same information but with the same order

country_info = {
    "population": {
        "brazil": "209 millions",
        "france": "70 millions",
        "usa": "328 millions",      
    },
    "capital": {
        "brazil": "Brasilia",
        "france": "Paris",      
        "usa": "Washington"
    },
    "language": {
        "brazil": "Portuguese",
        "france": "French",     
        "usa": "English",
    }
}

Although list would be preferred, but since python dict is now maintaining order( Python 3.6 onwards) you can try something like

sorted_dict = {k1: dict(sorted(country_info[k1].items(), key=lambda x: x[0])) for k1 in country_info.keys()}
{'population': {'brazil': '209 millions',
  'france': '70 millions',
  'usa': '328 millions'},
 'capital': {'brazil': 'Brasilia', 'france': 'Paris', 'usa': 'Washington'},
 'language': {'brazil': 'Portuguese', 'france': 'French', 'usa': 'English'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM