#πŸ”’ Iterating over a list value in a dictionary list.

16 messages Β· Page 1 of 1 (latest)

sour tree
#

Hey folks so I am making a tic tac toe game.

I was wondering, how I Iterate over each item in a list. I am using keys as values for the rows and then the index of the list is a column value.


gameboard = { 1: ["[ ]","[ ]", "[ ]"],
             2: ["[ ]","[ ]", "[ ]"],
             3: ["[ ]","[ ]", "[ ]"]
}

for key in gameboard:
    print(gameboard[key])```

I'm confused. How would I iterate over each invididual list item? 

I am aware also, that each item in the list is a string, how to I get the program to treat not iterate over each character  - but the string itself? 

Thanks in advance.
left stumpBOT
#

@sour tree

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

finite maple
#

gameboard[key] is a list. You can just iterate that. The more idiomatic way would be to use values though if you don't actually need the key (or items if you do):

for row in gameboard.values():
    # Use row list
sour tree
sour tree
sour tree
finite maple
sour tree
crisp cosmos
#

You would need to enumerate the columns then to get the column index

#

You might find it easier to separate out the representation of the gameboard with the actual data that you will be parsing as part of your game logic, lots of these kind of projects have something like a draw_board function that takes in the data and draws it however and just represents the underlying game data as ints or bools or whatever makes the most sense

sour tree
#

i figured it out, thanks

sour tree
rigid solar
#
for row in gameboard:
    for i, column in enumerate(gameboard[row], start=1):
        if column != "[ ]":
            print(f"That square is occupied at row {row}, column {i} ")
#

your index(...) version won't work, if you got more than one [X] in a row, as it would always pick the first one

left stumpBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.