0

So my plan here is simple, I want to store some information in a JSON file and, later in the code, I plan to look in the JSON file for one random piece among all information I stored previously and, after that, delete the specific one I used.

I've been using the following code for randomizing the piece of information I'm getting and trying to delete it from the JSON file:

sucesso = None
while sucesso is None:
    try:
        procurador = random.randint(1,10)
        idselecionado = datapass[procurador]
        sucesso = 1
    except:
        print("ainda procurando...")
        pass
del datapass[procurador]

And the JSON file is very basic, like this:

["1fFTHMtvoZHIcJQBK75MS22aM-UL5ucKx", "1PtINIlElccwKuN26gqdJmhA1CtctFO--", 
 "1sT_AjnNTtRCWsIkzC9SJc1L9XvwTqV7u", "19wnN_RoCQZZ5ykRy6DLxq6YNTkIwZV5s"]

A couple of things that are important on this:

  • The first one on the JSON file is not supposed to be taken, ever.
  • Normally, there will be more than ten id's on the JSON file, but I don't think there will be a problem with that since the while will rerun if the random one is not ok
  • The code goes into the first part (the try) but it doesn't go all the way to the end, basically stops at the randint, and then it prints "ainda procurando..." from the except and finally closes without running properly.
martineau
  • 119,623
  • 25
  • 170
  • 301
Gevezo
  • 364
  • 3
  • 17
  • 1
    The question is really how to remove the item from a *list*. The fact that your data came from JSON doesn't matter any more once you've read the file and created the list from it. – Karl Knechtel Mar 15 '21 at 18:43
  • Anyway, it's helpful to ask an actual *question*. It appears that the primary issue here is that you *get an error* with the code, but you don't know why because your `except` block catches every possible error and then prints an unhelpful message. The first thing you should do is *figure out what the error is*, by not doing that. The second thing you should do is *tell us* what the error is, and *explicitly ask* about it. – Karl Knechtel Mar 15 '21 at 18:44
  • If the same ID appears multiple times in the list, should that make it more likely to be chosen? If it is chosen, should all the occurrences be removed? If only one should be removed, does it matter which one (i.e., is it okay if only the first appearance ever is removed, or should they all be equally likely to be removed)? – Karl Knechtel Mar 15 '21 at 18:50

1 Answers1

0

well asserting your JSON file is list type.

json = []
def procedure(json):
    return json.pop(random.randint(1, len(json) - 1))

.pop() returns you a value that you can use by for example giving the result of function a name, like

result = procedure(json)
    

not only it return your desirable random value but also deletes it from that list.

#P.S. json[1:] means that random.choice uses only values from index 1 and not less.

polukarp
  • 54
  • 7