0

I am trying to iterate through a json response to get the elements for each array element in the response and add those to a new json object. I am making multiple calls that get a new json response, but also could return the same id from a previous call. I want to loop through all of the calls and have a list of unique id the end.

example json response

[{"firstName" : "John",
  "lastName"  : "Doe",
  "id:"       : "123542"
  },
  {"firstName" : "Jane",
  "lastName"  : "Doe",
  "id:"       : "123"
  },
  {"firstName" : "Harry",
  "lastName"  : "dude",
  "id:"       : "653"
  }
 ]

What I have right now but doesn't remove the dups. It just adds every single

new_members = []
for team in teams
    if team["name"] == "example":
        members = call_to_get_members.json()

        for member in members:
            new_member = {"firstName": member["firstName"], "lastName": member["lastName"]}
            if member not in new_members:
                new_members.append(new_member)
                break
4
  • if you only want one occurance, why not use sets? Commented May 4, 2015 at 19:03
  • @Karl dicts are not hashable, so can not be placed in a set. The OP would need to use tuples. Commented May 4, 2015 at 19:17
  • @kdopen the user data from the json is very hashable, such as the id field which he seems to indicate is a unique field. Commented May 4, 2015 at 19:20
  • Yes it is, but the OP is creating a dict. This code has many more problems than the one they are asking about, at least if I'm reading the 'spec' correctly for the problem they need to solve. I've seen that call_to_get_members before so I think this is an assignment. Commented May 4, 2015 at 19:22

1 Answer 1

1

I believe you have a typo in this line:

new_member = {"firstName": member["firstName"] + "lastName": member["lastName"]}

The + should be a comma.

The reason it is adding every entry lies in this if statement

if member not in new_members:

I believe you want

if new_member not in new_members:

Without seeing the output of call_to_get_members.json(), I have to assume it returns a list of dicts, each containing the first name, last name, and user id for each member. Thus, member will never match anything in new_members as the dicts in that list do not have an id field.

This results in the append happening every time.

Sign up to request clarification or add additional context in comments.

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.