Search code examples
pythonflaskuuid

Access one item from a dict and store it into a variable


I am trying to get all the "uuid"'s from an API, and the issue is that it is stored into a dict (I think). Her is how it looks on the API:

{"guild": {
        "_id": "5eba1c5f8ea8c960a61f38ed",
        "name": "Creators Club",
        "name_lower": "creators club",
        "coins": 0,
        "coinsEver": 0,
        "created": 1589255263630,
        "members":
            [{  "uuid": "db03ceff87ad4909bababc0e2622aaf8",
                "rank": "Guild Master",
                "joined": 1589255263630,
                "expHistory": {
                "2020-06-01": 280,
                "2020-05-31": 4701,
                "2020-05-30": 0,
                "2020-05-29": 518,
                "2020-05-28": 1055,
                "2020-05-27": 136665,
                "2020-05-26": 34806}}]
        }
    }

Now I am interested in the "uuid" part there, and take note: There is multiple players, it can be 1 to 100 players, and I am going to need every UUID.

Now I have done this in my python to get the UUID's displayed on the website: try:

f = requests.get(
            "https://api.hypixel.net/guild?key=[secret]&id=" + guild).json()
        guildName = f["guild"]["name"]
        guildMembers = f["guild"]["members"]
        members = client.getPlayer(uuid=guildMembers) #this converts UUID to player names
        #I need to store all uuid's in variables and put them at "guildMembers"

And that gives me all the "UUID codes", and I will be using client.getPlayer(uuid=---) to convert the UUID into the Player Names. I have to loop through each "UUID" into that code client.getPlayer(uuid=---) . But first of I need to save the UUID'S in variables, I have been doing members.uuid to access the UUID on my HTML file, but I don't know how you do the .uuid part in python

If you need anything else, just comment :)


Solution

  • List comprehension is a powerful concept:

    members = [client.getPlayer(member['uuid']) for member in guildMembers]
    

    Edit: If you want to insert the names back into your data (in guildMembers), use a dictionary comprehension with {uuid: member_name,} format:

    members = {member['uuid']: client.getPlayer(uuid=member['uuid']) for member in guildMembers}
    

    Than you can update guildMembers with your results:

    for member in guildMembers:
        guildMembers[member]['name'] = members[member['uuid']]