How do I search and find a specific value in a hash in a list? Python

48 views Asked by At

I am an amateur Python user, so bear with me. I created a list, and filled it with hashes. But I am having trouble, because I need to search the entire list to find the first hash with a specific value and update it. Does anyone know how?

character = [{"No": 1, "Name":"Jeff", "Level": 29, "Health": 290},
             {"No": 2, "Name":"Bill", "Level": 31, "Health": 310},
             {"No": 3, "Name":"EMPTY", "Level": 0, "Health": 0},
             {"No": 4, "Name":"EMPTY", "Level": 0, "Health": 0},
             {"No": 5, "Name":"EMPTY", "Level": 0, "Health": 0},
             {"No": 6, "Name":"EMPTY", "Level": 0, "Health": 0}]

In this code, I need to find the first instance of the empty name, and update its hash with another hash

I tried to use indexing, but it did not work, saying "Invalid Syntax"

x = character.index("EMPTY")
character[x].update(player)
print(character)
3

There are 3 answers

0
Wang Jun Rui On

yea,list can't use index method directly。 should used linear search to catch 'Name' == 'Empty'。

0
Lawrence On

I would be inclined to only populate the character list with active players, rather than empty ones. That way you can append new players directly to the list when they're created.

Nevertheless, this should give you what you're after:

# create a new player. NOTE: "No" is updated when appending to character list
player = {"No": 1, "Name":"Player", "Level": 30, "Health": 300}

# find the character index
idx = 0
for c in character:
    if c['Name'] == 'EMPTY':
        break
    else:
        idx += 1

# update player number
player['No'] = idx + 1


# replace element in list
character[idx] = player
0
Shahriar Rahman Zahin On

Here's how you can update the first occurrence:

character = [{"No": 1, "Name":"Jeff", "Level": 29, "Health": 290},
             {"No": 2, "Name":"Bill", "Level": 31, "Health": 310},
             {"No": 3, "Name":"EMPTY", "Level": 0, "Health": 0},
             {"No": 4, "Name":"EMPTY", "Level": 0, "Health": 0},
             {"No": 5, "Name":"EMPTY", "Level": 0, "Health": 0},
             {"No": 6, "Name":"EMPTY", "Level": 0, "Health": 0}]


player = {"No": 7, "Name":"Alex", "Level": 25, "Health": 250}

for character_hash in character:
    if character_hash["Name"] == "EMPTY":
        character_hash.update(player)
        break  # Break out of the loop after updating the first empty character

print(character)