Please convert this php code into python code. thank you! {Code...} is simply to sort the array in reverse order and convert it to json format. Please convert this php code into python code. thank you!
// Inverted sorting function my_sort ($ a, $ B) {if ($ a = $ B) return 0; return ($ a <$ B )? 1:-1 ;}$ arr = array ('AAA' => 5, 'BBB '=> 3, 'CCC' => 4); usort ($ arr, "my_sort"); echo json_encode ($ arr );
Simply put, the array is sorted in reverse order and then converted to json format.
Reply content:
Please convert this php code into python code. thank you!
// Inverted sorting function my_sort ($ a, $ B) {if ($ a = $ B) return 0; return ($ a <$ B )? 1:-1 ;}$ arr = array ('AAA' => 5, 'BBB '=> 3, 'CCC' => 4); usort ($ arr, "my_sort"); echo json_encode ($ arr );
Simply put, the array is sorted in reverse order and then converted to json format.
The associative array in PHP is an ordered mapping (ordered ing ).
This indicates that the dictionary in Python is not completely equal to the associative array.
Second, I do not know that the json scheme does not support ordered mapping, so if you want to complete this task, you may need:
Use the ordered ing object in Python:OrderedDict
(Please refer to OrderedDict)
PendingOrderedDict
Thinklist
Againjson
When you want to use this token, you mustjson
Load inlist
Restore againOrderedDict
Below isPython3For your exam:
Generation:
import jsonfrom collections import OrderedDict# using OrderedDictarr = {"aaa":5,"bbb":3,"ccc":4, "ddd":7}arr = OrderedDict(sorted(arr.items(), key=lambda item: item[1], reverse=True))# or you can create an OrderedDict directly:# arr = OrderedDict([('aaa', 5), ('bbb', 3), ('ccc', 4), ('ddd', 7)])print(arr)# listarr = list(arr.items())print(arr)# json dumpjson_arr = json.dumps(arr)print(json_arr)# json loadarr = OrderedDict(json.loads(json_arr))print(arr)
Result:
OrderedDict([('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)])[('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)][["ddd", 7], ["aaa", 5], ["ccc", 4], ["bbb", 3]]OrderedDict([('ddd', 7), ('aaa', 5), ('ccc', 4), ('bbb', 3)])
P.S. anyone who doesn't know is welcome to discuss with me. we can discuss it again.
import jsonarr={"aaa":5,"bbb":3,"ccc":4}print json.dumps(sorted(arr.values(),reverse=True))#'[5, 4, 3]'
Python code (after transformation)
#! /Usr/bin/env python # encoding: utf-8import jsonif _ name _ = '_ main _': myDict = {'AAA': 5, 'BBB ': 6, 'CC': 777} outDic = sorted (myDict. iteritems (), key = lambda asd: asd [1], reverse = True) print 'Dictionary before sorting, similar to the php array 'print myDict print 'and json output after sorting: 'print json. dumps (outDic)
Output:
/System/Library/Frameworks/Python. framework/Versions/2.7/bin/python2.7/Users/luyh/www/python/lesson1/pysort. the dictionary before sorting py, similar to the php array {'AAA': 5, 'BBB ': 6, 'CCC': 777}. after sorting, the json output is [["ccc ", 777], ["bbb", 6], ["aaa", 5] Process finished with exit code 0