json.dump() and sorted() dict

Ref:

http://www.cnblogs.com/BeginMan/p/3193081.html

http://www.cnblogs.com/BeginMan/p/3178103.html

 

json.dump() returns an encoded string based on given data.

It transforms the type from tuple to list.

import json        dict1 = [{'a': 'A', 'b': 123, 'c':(2, 4)}]encoded = json.dumps(dict1)print 'Original dict:', dict1print 'Encoded:', encoded

 

Output:

Original dict: [{'a': 'A', 'c': (2, 4), 'b': 123}]
Encoded: [{"a": "A", "c": [2, 4], "b": 123}]

Here you can see the value of key 'c' becomes a list.

************************************************************

sorted() can be used to sort by key or value in a dict. If you want to use reversed order, you should explicitly pass the argument.

import json  data1 = {'b':789,'c':456,'a':123}  d1 = json.dumps(data1,sort_keys=True)  print 'Encoded unsorted dict:', d1print 'Original dict unsorted:', data1print 'Original dict SORTED BY VALUE:', sorted(data1.iteritems(), key=(lambda d:d[1]), reverse=True)

 

Output:

Encoded unsorted dict: {"a": 123, "b": 789, "c": 456}
Original dict unsorted: {'a': 123, 'c': 456, 'b': 789}
Original dict SORTED BY VALUE: [('a', 123), ('c', 456), ('b', 789)]

 

key=(lambda d:d[0])

means to sort by key.

sorted(data1.iteritems(), key=(lambda d:d[0]), reverse=True)

means to sort by key reversely.

 

Notes:

data1 is iterable, while d1 is a string which is not iterable.

 

Make sure you are not using 'reversed' which is a function instead of an argument.

revsd = reversed([1,2,3,4,5])    print 'reversed object:', revsdprint 'reversed list:', list(revsd)

 

Output:

reversed object: <listreverseiterator object at 0x0252E6D0>
reversed list: [5, 4, 3, 2, 1]