Create a ranking with json. Sort by specific properties.

Asked 2 years ago, Updated 2 years ago, 36 views

{
    "720924012909166682": {
        "770571591422836757": {
            "lvl": 6,
            "exp": 12
        },
        "409679882327687168": {
            "lvl": 1,
            "exp": 0
        },
        "507504723184844813": {
            "lvl": 5,
            "exp": 20
        }
    }
}

Inside the json file to use.

with open('path', 'r') as f:
    lvs = json.load(f)

The json file was loaded using .

v1 = json.loads (json.dumps(lvs[str("first key"), sort_keys=True))

The key inside the first key and the values are retrieved. And

write = []
~~~ # Specify write
print("\n".join(write))

You are about to print it out using .

However, all 'lvl' values inside v1 in the write list were taken and blocked where you tried to sort them in high order. I'd appreciate it if you could help me if you know what to do.

Note that the output format is (using json internal)

LV.6 770571591422836757
Lv.5 507504723184844813
LV.1 409679882327687168

I want to do this.

json python

2022-09-20 19:17

1 Answers

import json

with open("dat.json") as f:
    lvs = json.load(f)

v1 = lvs["720924012909166682"]

v1_sorted_by_lvl = sorted(v1.items(), key=lambda e: e[1]["lvl"], reverse=True)

write = []
for k, v in v1_sorted_by_lvl:
    write.append(f'LV.{v["lvl"]} {k}')

print("\n".join(write))


2022-09-20 19:17

If you have any answers or tips

Popular Tags
python x 4647
android x 1593
java x 1494
javascript x 1427
c x 927
c++ x 878
ruby-on-rails x 696
php x 692
python3 x 685
html x 656

© 2024 OneMinuteCode. All rights reserved.