Home > Mobile >  Python Nested Dictionary "None" coming up when it's done iterating
Python Nested Dictionary "None" coming up when it's done iterating

Time:10-23

I'm doing the Automate the Boring Stuff with Python and I'm confused why the "None" keeps coming up once it's done iterating through the dictionary. I'm trying to count how many chess pieces there are. I know I'm only counting the spaces currently.

Originally I had.

chessPieces = { 'player1': {'1a': 'wpawn', '1b': 'wknight', '1c': 'wbishop'},
                'player2': {'8a': 'bpawn', '8b': 'bknight', '8c': 'bbishop'}}

def isValidChessBoard(d):
    numPieces = 0
    for k in d.keys():
        for v in d[k].keys():
            numPieces  = 1
    print(numPieces)

Then I thought maybe adding a while loop to count the number of keys might help avoid it, but I'm getting the same result. Any idea why this is happening, or what am I not understanding correctly?

chessPieces = { 'player1': {'1a': 'wpawn', '1b': 'wknight', '1c': 'wbishop'},
                'player2': {'8a': 'bpawn', '8b': 'bknight', '8c': 'bbishop'}}


def isValidChessBoard(d):
    numPieces = 0
    players = len(d.keys())
    while players:
        for k in d.keys():
            players -= 1
            for v in d[k].keys():
                numPieces  = 1
        print(numPieces)

print(isValidChessBoard(chessPieces))

Output
6
None

Thanks in advance,

CodePudding user response:

You have a print in the function, then you have print for the RETURN of the function. Nothing is being returned from the function so the second print statement prints nothing! Very close. This would make more sense to me to write.

chessPieces = { 'player1': {'1a': 'wpawn', '1b': 'wknight', '1c': 'wbishop'},
            'player2': {'8a': 'bpawn', '8b': 'bknight', '8c': 'bbishop'}}


def CountChessPieces(d):
    numPieces = 0
    for k in d.keys():
        for v in d[k].keys():
            numPieces  = 1
    return numPieces

print(CountChessPieces(chessPieces))
  • Related