Reputation: 26637
I have a python dictionary that I want to sort according to name:
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 %}
Upvotes: 2
Views: 426
Reputation: 2346
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']))
Upvotes: 3
Reputation: 776
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.
Upvotes: 1
Reputation: 11235
you should try
location_map_india = sorted(location_map_india.items(), key=lambda x: x[1]['name'])
Upvotes: 1
Reputation: 36725
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.
Upvotes: 6