Optimize if and elif statement in python

Viewed 27
 @bot.listen(hikari.GuildMessageCreateEvent)
    async def message_count(event):
        if event.author_id == 2077187399893646:
            wks.update('B3', int(wks.acell('B3').value) + 1)
        elif event.author_id == 5698347053572369:
            wks.update('B4', int(wks.acell('B4').value) + 1)
        elif event.author_id == 495226377080012800:
            wks.update('B5', int(wks.acell('B5').value) + 1)
        elif event.author_id == 4270132384522260:
            wks.update('B6', int(wks.acell('B6').value) + 1)
        elif event.author_id == 9929743815734492:
            wks.update('B7', int(wks.acell('B7').value) + 1)
        elif event.author_id == 10163219484660768:
            wks.update('B8', int(wks.acell('B8').value) + 1)
        elif event.author_id == 9564825465720691:
            wks.update('B9', int(wks.acell('B9').value) + 1)

Is there an alternative way to check the condition for author_id that's more optimized than using multiple if and elif? wks.acell(B).value just check a value in cell B in my google sheet, wks.update(A,1) change the value of cell A to 1

2 Answers

try to create a dict with keys as your author_id and values your B values somethings like this :

 @bot.listen(hikari.GuildMessageCreateEvent)
    async def message_count(event):
      mapping_dict= {2077187399893646:'B3',5698347053572369:'B4',.........}
      wks.update(mapping_dict[event.author_id],int(wks.acell(mapping_dict[event.author_id]).value) + 1)

Store the author_id and that 'B' property in a dictionary, and then modify the method as follows:

authors = {
    2077187399893646: 'B3',
    5698347053572369: 'B4',
    495226377080012800: 'B5',
    ...
}

@bot.listen(hikari.GuildMessageCreateEvent)
    async def message_count(event):
        if event.author_id in authors.keys():
            wks.update(authors[event.author_id], int(wks.acell(event.author_id).value) + 1)
        else:
            print('Author not registered in the database')

Of course it would be better to obtain authors from a persistent memory storage, such as a json file, or a database of your choice. Hope it helps.

Related