1

I have this json structure:

{
  "http://marvel.wikia.com/wiki/Virginia_Potts_(Earth-33900)": [
    "/wiki/Virginia_Potts_(Earth-616)",
    "/wiki/Earth-33900",
    "/wiki/Stark_Industries_(Earth-33900)",
    "/wiki/AAFES_Vol_1_15",
    "/wiki/Washington_State",
    "/wiki/Pepper_Potts",
    "/wiki/Tom_Grummett",
    "/wiki/William_Harms",
    "/wiki/Virginia_Potts_(Earth-616)#Abilities",
    "/wiki/Seattle"
  ],
  "http://marvel.wikia.com/wiki/Virginia_Potts_(Earth-5631)": [
    "/wiki/Pepper_Potts",
    "/wiki/Earth-5631",
    "/wiki/Iron_Man_and_Power_Pack_Vol_1_1",
    "/wiki/Marc_Sumerak"
  ],
...

I want to iterate over the json and for each item verify if one of its links (it's a list of links) is not contained in another json with a complete list of characters (in the following code it's characters). In this case I want to eliminate the link from the list. At the end save the dictionary (links_ref) in a file.

for item in links_ref:
        for link in links_ref[item]:
            if link not in characters:
                links_ref[item].pop(link)
json.dump(links_ref, open('links_raf.json', 'w'))

This code of course doesn't work, I tried also with del link but, even if it didn't launch an exception, it didn't remove the link from the list too.

Hope someone can help me, I'm new to python so I'll be more than happy if you can suggest a better solution to my problem. Thank you

2 Answers 2

3

You can't modify the list while you are iterating over it. You can make use of list comprehensions though in order to filter out the links:

for item, links in links_ref.items():
    links_ref[item] = [link for link in links if link in characters]
Sign up to request clarification or add additional context in comments.

1 Comment

Wasn't exactly my solution but it helped me a lot. Thanks
0

Immutable way:

filtered_links_ref = {i: [l for l in links_ref[i] if l not in characters] for i in links_ref}

Or try to use sets:

character_set = frozenset(characters)
filtered_links_ref = {i: frozenset(links_ref[i]) - character_set for i in links_ref}

Comments

Your Answer

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.