This article mainly introducesPythonProgrammingHow to sort dictionary elements in a list, involving Python's operating skills related to traversing, reading, and converting list and dictionary elements , Friends who need it can refer to
The example of this article describes the method of sorting dictionary elements in the list using Python programming. Share it with everyone for your reference, the details are as follows:
Content directory:
1. Origin of the problem
2. Sorting dictionary elements in the list
3. Compare json (ignoring the order of the dictionaries in the list)
1. Origin of the problem
##jsonObjecta,b
a = '{"ROAD": [{"id": 123}, {"name": "no1"}]}' b = '{"ROAD": [{"name": "no1"}, {"id": 123}]}'
list(set()) combination. However, if the list contains dictionary elements, list(set cannot be used) ()) combination, see the prompt:
>>> a = [{'a':1, 'b':2}, {'c':3}] >>> a [{'a': 1, 'b': 2}, {'c': 3}] >>> b = set(a) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> b = set(a) TypeError: unhashable type: 'dict'
2. Sort the dictionary elements in the list
Fortunately, the list has the>>> p = [{'b': 2}, {'a': 1, 'c': 3}] >>> q = [{'a': 1, 'c': 3}, {'b': 2}] >>> p [{'b': 2}, {'a': 1, 'c': 3}] >>> q [{'a': 1, 'c': 3}, {'b': 2}] >>> pp = sorted(p) >>> qq = sorted(q) >>> pp [{'b': 2}, {'a': 1, 'c': 3}] >>> qq [{'b': 2}, {'a': 1, 'c': 3}] >>> pp == qq True >>> p == q False
3. Compare json (ignoring the order of dictionaries in the list)
import json def compare_json(a, b): aa = json.loads(a) bb = json.loads(b) len_a = len(aa) len_b = len(bb) if len_a != len_b: return False else: for key in aa: if not bb.has_key(key): return False else: if sorted(aa[key]) != sorted(bb[key]): return False return True if name == "main": a = '{"ROAD": [{"id": 123}, {"name": "no1"}]}' b = '{"ROAD": [{"name": "no1"}, {"id": 123}]}' print compare_json(a, b)
The above is the detailed content of Detailed explanation of how to sort dictionary elements in a list using Python programming. For more information, please follow other related articles on the PHP Chinese website!