find common values from json file

Question:

I’m trying to find users from a JSON file that have the same "p1" as the input user, and then return the names of all of them.
I’m new to coding, sorry if this code looks bad

user1 refers to the input user

async def find_common_p1(user1):
    users = await get_json()
    for user in users:
        if users[str(user)]["p1"] == users[str(user1.id)]["p1"]:
            return users[str(user)]["name"]


async def get_json():
    with open("the json file", "r") as f:
        users = json.load(f)
    return users

Inside the json file looks like:

{"user_1_id": {"name": "user_1", "p1": False}, 
"user_2_id": {"name": "user_2", "p1": True}, 
"user_3_id": {"name": "user_3", "p1": True}}
Asked By: user20124814

||

Answers:

You are on the right track, your code:

async def find_common_p1(user1):
    users = await get_json()
    for user in users:
        if users[str(user)]["p1"] == users[str(user1.id)]["p1"]:
            return users[str(user)]["name"]

This will return the first user with a matching "p1". To return all users with a matching "p1" you have to remember all the users who match then return it at the end of the function. So like this

async def find_common_p1(user1):
    users = await get_json()
    users_with_matching_p1 = []
    for user in users:
        if users[str(user)]["p1"] == users[str(user1.id)]["p1"]:
            users_with_matching_p1.append(users[str(user)]["name"])
    
    return users_with_matching_p1
Answered By: Ryan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.