1

I am trying to read some JSON for a leaderboard for my discord bot, formatted like this:

{"915714438273826858": 
 [
 {"915714438823313420": 
 ["", 0]
 }, 
 [
 {"747797252105306212": 
 [1, 2]
 },
 {"695390884291674153": 
 [3, 8]
 }
 ]
 ]
}

I can read the first part fine, but reading this list here is giving me some problems:

[
 {"747797252105306212": 
 [1, 2]
 },
 {"695390884291674153": 
 [3, 8]
 }
]

How can I read the values of each of the dictionaries in the list? For example, say I want to get the dictionary with the key "747797252105306212"'s sub-list, so I could get [1,2]?

Currently, my method is to get all the keys in the larger list using

all_keys = set().union(*(d.keys() for d in lb))
all_keys = list(all_keys)

and then using the order in all_keys to call the dictionary. For example, sometimes, all_keys shows ["747797252105306212","695390884291674153"], and I can call the dictionaries using the above order, as "747797252105306212"'s index is 0 in both all_keys and in the JSON list. However, sometimes all_keys is out of order, making the program call the wrong dictionary, causing this method to be obsolete. Is there any way to fix this, or a different method?

Azat Ibrakov
11.1k9 gold badges43 silver badges58 bronze badges
asked Apr 19, 2022 at 22:16

1 Answer 1

1

If I understand your issue correctly, the issue is that sets don't maintain insertion order.

You can maintain a list (which maintains order) and a separate set (for quickly checking whether you've seen a key already). For each key that you see, check whether it's a member of the set; if not, add it to the list and the seen keys set:

result = []
seen_keys = set()
for item in data:
 for key in item:
 if key not in seen_keys:
 seen_keys.add(key)
 result.append(key)
 
print(result)

With the given data, this will (deterministically!) output:

['747797252105306212', '695390884291674153']
answered Apr 19, 2022 at 22:23
9
  • Thanks for the quick response! This looks like what I wanted, and I will test it when I get a chance. Commented Apr 19, 2022 at 22:26
  • Awesome! Let me know if you have any questions. Commented Apr 19, 2022 at 22:30
  • 1
    Much shorter way to do an order-preserving dedupe of x is [*{}.fromkeys(x)]. Commented Apr 20, 2022 at 1:52
  • 1
    @TheFeatherMan No problem, happy to help! Commented Apr 20, 2022 at 2:06
  • 1
    @BrokenBenchmark Anything iterable that you want to dedupe. Commented Apr 20, 2022 at 2:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.