开发者

Sorting a python dictionary by name?

I have a python dictionary that I want to sort according to nam开发者_运维技巧e:

location_map_india = {
  101: {'name': 'Andaman & Nicobar Islands', 'lat': 11.96, 'long': 92.69, 'radius': 294200},  
  108: {'name': 'Andhra Pradesh', 'lat': 17.04, 'long': 80.09, 'radius': 294200},
...
}

It doesn't come out the way I expect it. I tried:

location_map_india = sorted(location_map_india.iteritems(), key=lambda x: x.name)

The above didn't work. What should I do?

Update

The following was allowed and behaved as expected. Thanks for all the help. Code:

location_map_india = sorted(location_map_india.iteritems(), key=lambda x: x[1]["name"])

Template:

{% for key,value in location_map_india %}<option value="{{key}}" >{{value.name}}</option>{% endfor %}


You are close. Try:

location_map_india = sorted(location_map_india.iteritems(), key=lambda x: x[1]["name"])

but the result would be a list not a dict. dict is orderless.


If you're using python 2.7 or superior, take a look at OrderedDict. Using it may solve your problem.

>>> OrderedDict(sorted(d.items(), key=lambda x: x[1]['name']))


you should try

location_map_india = sorted(location_map_india.items(), key=lambda x: x[1]['name'])


If you are using a dictionary that must have order in any way, you are not using the correct data structure.

Try list or tuples instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜