简体   繁体   English

从 json 文件中查找共同值

[英]find common values from json file

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.我正在尝试从 JSON 文件中查找与输入用户具有相同“p1”的用户,然后返回所有这些用户的名称。 I'm new to coding, sorry if this code looks bad我是编码新手,抱歉,如果这段代码看起来不好

user1 refers to the input user user1指的是输入用户

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: json 文件内部如下所示:

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

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".这将返回具有匹配“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要返回具有匹配“p1”的所有用户,您必须记住所有匹配的用户,然后在 function 的末尾返回它。就像这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM