0

Having a JSON-like structure:

{
    "shopping_list": [
        {
            "level": 0,
            "position": 0,
            "item_name": "Gold Badge"

        },
        {
            "level": 1,
            "position": 10,
            "item_name": "Silver Badge"

        },
        {
            "level": 2,
            "position": 20,
            "item_name": "Bronze Badge"

        }
    ]
}

I'm trying to sort the list by key.

However, when trying to get them by:

k = [c.keys()[0] for c in complete_list["shopping_list"]]

I get TypeError: 'dict_keys' object does not support indexing.

  1. How to get keys?
  2. How to sort the list by specified key?
milanbalazs
  • 4,811
  • 4
  • 23
  • 45
AbreQueVoy
  • 1,748
  • 8
  • 31
  • 52
  • 2
    What do you mean by _sort the list by key_? – DjaouadNM Sep 10 '19 at 09:05
  • If you want a list of the keys, it's... `list(c.keys())` (or just `list(c)`). But which key do you want to sort by? Try e.g. `sorted(complete_list["shopping_list"], key=lambda c: c["item_name"])`. – jonrsharpe Sep 10 '19 at 09:06
  • `sorted(complete_list["shopping_list"], key=lambda x: x['level'])` – ekhumoro Sep 10 '19 at 09:09
  • @MrGeek: it seems I wasn't clear enough: I'd like to have the entries (dictionaries) sorted by value of specified key. – AbreQueVoy Sep 10 '19 at 09:10

2 Answers2

1

Try this to get the keys in a list of lists :

d = {
    "shopping_list": [
    ...
}
k = [list(c.keys()) for c in d["shopping_list"]]
print(k)

Output :

[['item_name', 'level', 'position'], ['item_name', 'level', 'position'], ['item_name', 'level', 'position']]

However even if you wanted to sort this list of lists based on some specific key value say value for "level" key or "position" key, the list of lists would remain same.

Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
1

Here it is (admitting the key you mention is 'level'):

k = sorted([c for c in complete_list["shopping_list"]], key=lambda x: x['level'])

print(k) 
# >> [{'level': 0, 'position': 0, 'item_name': 'Gold Badge'}, {'level': 1, 'position': 10, 'item_name': 'Silver Badge'}, ...
olinox14
  • 6,177
  • 2
  • 22
  • 39