I am trying to parse a JSON output and if a Index has the userId of 5, I want to ignore it. The problem is that it still does not ignore it.
Here is how i read the json (works):
import json
import urllib.request
url = "https://jsonplaceholder.typicode.com/posts"
data = urllib.request.urlopen(url).read().decode()
site_info =json.loads(data)
for info in site_info:
print(f"{}, {}, {}, {}".format(info["userId"], info["id"],
info["title"], info["body"]))
Here is how I prepare a list of userIds to inspect (removal of 5 does not work):
mylist= [{"userId":1}, {"userId":2}, {"userId":3}, {"userId":4}, {"userId":5},
{"userId":6}, {"userId":7}, {"userId":8}, {"userId":9}, {"userId":10}]
for i in range(len(mylist)-5, -5, -5):
print(i)
if mylist[i]["userId"] == 5:
mylist.pop(i)
print (mylist)
I also need to use .pop
as part of the assignment.
CodePudding user response:
Your code does exactly what you told it to:
- it checks the positions 5 and 0 on your
mylist
n - if either had a
mylist[i]["userId"] == 5
something would be done - neither has
mylist[i]["userId"] == 5
so it does nothing.
Beside that: NEVER change a list while iterating (unless you know how-to - you do not do it correctly).
You can remember indexes to pop and pop them seperately:
idx_to_delete = []
for idx,value in enumerate(mylist):
if value["userId"] == 5:
idx_to_delete.append(idx)
# reverse - because if you pop 2 and then 5 the popping of 2
# would lead to 5 now being 4 etc. if you pop the higher ones
# first you do not have that problem.
# reversed(idx_to_delete) == idx_to_delete[::-1]
for id in reversed(idx_to_delete):
mylist.pop(id)
To raise the quality of your question, you should
- remove all the JSON stuff - you never use site_info for your actual problem so it does not belong into a minimal reproducible example
- get rid of things that confuse you:
range(len(mylist)-5, -5, -5)
evaluates torange(10-5, -5, -5)
and results in5,0
if iterated - so replace it withfor i in (5,0):
. If you checkmylist[5]
andmylist[0]
you'll see that NEITHER has a["userId"] == 5
.
Your questions code would boil down to
mylist= [{"userId":1},{"userId":2},{"userId":3},{"userId":4},{"userId":5}, {"userId":6},{"userId":7},{"userId":8},{"userId":9},{"userId":10}] for i in (5,0): print(i) if mylist[i]["userId"] == 5: mylist.pop(i) print (mylist)
Why does the "userId" == 5 not get popped? List is unchanged?
If would probably be easier if you did
id_to_ignore = {5,}
mylist = [{"userId":id} for id in range(10) if id not in id_to_ignore]
# or as loop
# mylist = []
# for id in range(1,11):
# if id in id_to_ignore:
# continue
# mylist.append( {"userId":id})