Python programming to sort the list of dictionary elements

  • 2020-06-01 10:16:59
  • OfStack

This article demonstrates how the Python program sorts dictionary elements in a list. I will share it with you for your reference as follows:

Contents:

1. The origin of the problem
Sort the dictionary elements in the list
3. Compare json (ignore the order of dictionaries in the list)

1. The origin of the problem

b a json object


a = '{"ROAD": [{"id": 123}, {"name": "no1"}]}'
b = '{"ROAD": [{"name": "no1"}, {"id": 123}]}'

Features: key values for a,b, Python objects -- the list contains the same dictionary elements, but the order is different. If you ignore the order, how to determine if the two json are equal? Because the dictionary itself is sorted by its own buttons, and the list is sorted in the order in which it is added, sorting the dictionary elements in the list is easy. If the list is a normal element (not a dictionary), the list can be sorted by list(set()) combination. If the list is a dictionary element, list(set()) combination cannot be used.


>>> 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'

Hint that the dictionary is a non-hashing type (normal non-dictionary elements can be easily sorted by hashing).

So the essence of the problem is: how to sort the dictionary elements in a list.

Sort the dictionary elements in the list

Fortunately, the list has the sorted function. Try 1


>>> 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

You can see that ok, and you can see that the principle of sorting is the number of elements.

3. Compare json (ignore 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)

Details: when writing json, a = "{'road':1}" json. loads(a) error, a = '{"road:1}'

PS: for the operation of json, here are some practical json online tools for your reference:

Online JSON code validation, validation, beautification, formatting tools:
http://tools.ofstack.com/code/json

JSON online formatting tool:
http://tools.ofstack.com/code/jsonformat

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

json code online formatting/beautification/compression/editing/conversion tools:
http://tools.ofstack.com/code/jsoncodeformat

Online json compression/escape tool:
http://tools.ofstack.com/code/json_yasuo_trans

More Python related content interested readers to view this site project: "Python json operation skills summary", "Python coding skills summary", "Python data structure and algorithm tutorial", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has helped you with your Python programming.


Related articles: