Home > Mobile >  how to replace elif statements and shorten code
how to replace elif statements and shorten code

Time:09-29

here is my code at the moment, i was wondering if someone can help to shorten the code

def create_dice_dictionary(dice_list):
    
    dice_dictionary={1:0,2:0,3:0,4:0,5:0,6:0}
    
    for num in dice_list:
        
        if num==1:
            dice_dictionary[1] =1
        
        elif num==2:
            dice_dictionary[2] =1
     
        elif num==3:
            dice_dictionary[3] =1
        
        elif num==4:
            dice_dictionary[4] =1
       
        elif num==5:
            dice_dictionary[5] =1
       
        elif num==6:
            dice_dictionary[6] =1
    return dice_dictionary

CodePudding user response:

you can simply your like this:

def create_dice_dictionary(dice_list):
    
    dice_dictionary={1:0,2:0,3:0,4:0,5:0,6:0}
    
    for num in dice_list:    
        dice_dictionary[num] =1
        
    return dice_dictionary


res = create_dice_dictionary([1, 2, 3])
print (res)

CodePudding user response:

Counter-based answer with filtering out values other than 1-6

from collections import Counter


def create_dice_dictionary(dice_list):
    d = [d for d in dice_list if d in range(1, 7)]
    return Counter(d)


dice_list = [1, 5, 3, 6, 2, 2, 3, 5, 1, 5, 2, 4, 2, 5, 6, 7, 100, 5.5]

print(create_dice_dictionary(dice_list))

CodePudding user response:

To get the same output (assuming the input list only contains the values 1 to 6), you could use:

import collections

def create_dice_dictionary(dice_list):
    d = {k: 0 for k in range(1, 7)}
    d.update(collections.Counter(dice_list))
    return d

But if the result does not have to be a dictionary, and you don't need the dices with count 0, you could just use collections.Counter(dice_list) instead.

CodePudding user response:

Even shorter:

def create_dice_dictionary(dice_list):
    dice_dictionary = {k:0 for k in range(1,7)}
    for d in dice_list:
        dice_dictionary[d]  = 1
    return dice_dictionary
  • Related