0

I have a list of dictionaries. One of the fields of the dictionaries is "name". I am saving this list of dictionaries to file: with the command

json.dump(myList, fileName, indent=4)

but it is not being saved as I would like to. Since list data-structure is a structure that allows sorting, how can I save it as json array ordered by a field of the dictionary elements?

For example consider this list of dictionaries:

l =[{'name':'c', 'val' : 9},{'name': 'a', 'val': 10}, {'name': 'b', 'val': 10}, {'name': 'aa', 'val': 10}]

I would like as output a jsons like:

[
    {
        "name": "a",
        "val": 10
    },
    {
        "name": "aa",
        "val": 10
    },
    {
        "name": "b",
        "val": 10
    },
    {
        "name": "c",
        "val": 9
    }
]
roschach
  • 8,390
  • 14
  • 74
  • 124
  • Possible duplicate of [Sorting a list of dicts by dict values](https://stackoverflow.com/questions/10915391/sorting-a-list-of-dicts-by-dict-values) – Patrick Artner Jan 16 '19 at 15:46
  • Please note that many of those answers do not work in Python3 but only in Python2 because the dictionary changed. For this reason I do not think it is a duplicate – roschach Jan 16 '19 at 16:20
  • Dictionary methods such as `keys()`, `values()` and others do not return a `list` anymore (but `views` if I remember correctly), making for example the solution `sorted(a, key=dict.values, reverse=True)` invalid. – roschach Jan 16 '19 at 16:24
  • @That would not solve your problem, you are not sorting by _all_ values - you are sorting by one key's value ... so you do `l.sort(key=lambda d:d.get("name")` and are done. – Patrick Artner Jan 16 '19 at 16:26
  • this might be a better dupe: [how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) .. for me that is the 1st hit on google for `python sort list of dict by attribute` and there are 2-5 others floating around that lead to the same solution - now there are 3-6. – Patrick Artner Jan 16 '19 at 16:27

1 Answers1

1

You can sort by a specific key using the builtin sorted command. I think there are plenty of examples of this on here, but specifically for your problem:

l = sorted(l, key=lambda l: l['name'])
print(l)
# [{'name': 'a', 'val': 10},
#  {'name': 'aa', 'val': 10},
#  {'name': 'b', 'val': 10},
#  {'name': 'c', 'val': 9}]
Engineero
  • 12,340
  • 5
  • 53
  • 75