简体   繁体   中英

Why do I keep getting AttributeError: 'set' object has no attribute 'get'?

I'm trying to count the number of each specific suit from a hand inputted into the function. This is my current code:

def tally(h):
    hands = {''}
    hands.update(h)
    for i in h:
        if hands.get('♥'):
            heart += 1
        if hands.get('♣'):
            club += 1
        if hands.get('♦'):
            diamond +=1
        if hands.get('♠'):
            spade += 1
    suit = {
    '♥':heart,
    '♣':club,
    '♦':diamond,
    '♠':spade
    }
    return(suit)

but, I keep getting the error AttributeError: 'set' object has no attribute 'get'?

When you do hands = {''} , you are making a set , not a dictionary. Replacing this with hands = {} does the trick.

def tally(h):

    hands = {}
    hands.update(h)
    for i in h:
        if hands.get('♥'):
            heart += 1
        if hands.get('♣'):
            club += 1
        if hands.get('♦'):
            diamond +=1
        if hands.get('♠'):
            spade += 1
    suit = {
    '♥':heart,
    '♣':club,
    '♦':diamond,
    '♠':spade
    }
    return(suit)

More information can be found on the python documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM