Reputation: 331
I have a large dict, but similar in concept to this:
data = {'business1': {'1/2':20, '1/4':10, '1/3':30}, 'business2': {'1/2':10, '1/4':20, '1/3':30}}
I want to sort the nested dicts by date. I understand how to do this when no nesting is involved, as shown below. I created a list, and I append the key, value pairs to the list and then sort.
data = {'1/2':20, '1/4':10, '1/3':30}
sorted_data = []
for key,value in data.iteritems():
temp = (key,value)
sorted_data.append(temp)
sorted_data.sort(key = lambda item: item[0], reverse=False)
print sorted_data
The problem is how to do this when dicts in dicts are involved, such as what I first mentioned:
data = {'business1': {'1/2':20, '1/4':10, '1/3':30}, 'business2': {'1/2':10, '1/4':20, '1/3':30}}
Upvotes: 1
Views: 929
Reputation: 178
from collections import OrderedDict
for k,v in data.items():
data[k] = OrderedDict(sorted(v.items()))
print data
user input:
data = {'business1': {'1/2':20, '1/4':10, '1/3':30}, 'business2': {'1/2':10, '1/4':20, '1/3':30}}
output:
{'business2': OrderedDict([('1/2', 10), ('1/3', 30), ('1/4', 20)]), 'business1': OrderedDict([('1/2', 20), ('1/3', 30), ('1/4', 10)])}
Upvotes: 1
Reputation: 8709
>>> data = {'business1': {'1/2':20, '1/4':10, '1/3':30}, 'business2': {'1/2':10, '1/4':20, '1/3':30}}
>>> {i:sorted(data[i].items(), key=lambda x: x[0]) for i in data}
{'business2': [('1/2', 10), ('1/3', 30), ('1/4', 20)], 'business1': [('1/2', 20), ('1/3', 30), ('1/4', 10)]}
Upvotes: 0
Reputation: 36668
You haven't said what you want your results to look like, but I would assume you want them to look like this:
result = {'business1': [('1/2',20), ('1/3',30), ('1/4',10)],
'business2': [('1/2',10), ('1/3',30), ('1/4',20)]}
Here's how I would do it:
result = {}
for business_name, business_data in data.iteritems():
# The following is basically your single-data loop
sorted_data = []
for key,value in business_data.iteritems():
temp = (key,value)
sorted_data.append(temp)
sorted_data.sort(key = lambda item: item[0], reverse=False)
result[business_name] = sorted_data
Now, you could save a step. The for key,value in business_data.iteritems():
loop is basically repeating what dict.items()
does. So you could replace four lines with sorted_data = list(business_data.items())
. (The list()
call is unnecessary in Python 2 but doesn't hurt anything, and it's needed in Python 3. Since you didn't say which version you're using, I left it in so that my answer will work on either Python 2 or Python 3).
So the final version I would suggest is:
result = {}
for business_name, business_data in data.iteritems():
sorted_data = list(business_data.items())
sorted_data.sort(key = lambda item: item[0], reverse=False)
result[business_name] = sorted_data
Hope this helps.
Upvotes: 0