Home > Blockchain >  Function returning a key value from a dict within a list
Function returning a key value from a dict within a list

Time:11-03

I have a list that contains dicts - I want a function that returns a key value from a dict within that list. Explanation below.

The below function simulate_tournament takes a list as input and is supposed to return a string (not a list/dict) by way of indexing.

When I try to get the return value I need (a string which is the key value of a dict within the list) with return teams[0]['teams'], I am not able to. The error: TypeError: string indices must be integers. With return teams, I am getting the list containing the dict, which kind of works for me but is not desirable.

def simulate_tournament(teams):
    """Simulate a tournament. Return name of winning team."""
    teams = simulate_round(teams)
    if (len(teams) != 1):
        teams = simulate_tournament(teams)

    return teams[0]["team"]

However, when I change the code to the following, I am somehow able to get exactly the return value I need. No error.

def simulate_tournament(teams):
    """Simulate a tournament. Return name of winning team."""
    while (len(teams) > 1):
        teams = simulate_round(teams)

    return teams[0]["team"]

What am I missing here that I am getting an error in the first version of this function and not the second one?

CodePudding user response:

Your first function takes teams - a list of dicts - as a parameter and returns a name of a team. So the following line:

teams = simulate_tournament(teams)

makes no sense, because you are replacing your list of dicts with a string containing a team name. That is why

teams[0]["team"]

creates an error.

To use the function recursively, it has to return the same kind of data that it accepts as a parameter. This does not seem like a good use case for a recursive function - it creates confusion and doesn't achieve anything you couldn't do easily with a loop - so your second method is better.

  • Related