Python Dictionary - Help wanted to check same key data type

Hi Team

I wrote this code in response to dictionary practice question

Create a function called sum_even_keys that takes a dictionary named my_dictionary , with all integer keys and values, as a parameter. This function should return the sum of the values of all even keys.

def sum_even_keys(my_dictionary): 
  a = []
  for num in my_dictionary:
    if type(num) != int:
      a.append(False)
  if False in a:
    return "one of the values is not int"
  else:
    wanted = {val for num,val in my_dictionary.items() if num%2 ==0}
    return sum(wanted)

I wonder if there is a way to cut down each key data type check using some keyword. i checked online but couldn’t find satisfactory answer. Kindly help.

How can i improve this code?

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

looking at the requirements:

validation is not even needed

1 Like

Hi

I just wanted to make the code more intelligent. So in case validation is needed, what can be the solution?

thanks

1 Like

you would need to validate both keys and values given they are both suppose to be integers:

for key, value in my_dictionary.items():

then i would not use append, but rather i would return an error message directly:

if type(key) is not int or type(val) is not int:
  return "Some message"

or maybe even better to just throw an exception (ValueError could be good here)

1 Like

:ok_hand: awesome.

Do you think there is a method to check data type of each key and value in one go rather than using loop or if statement.

1 Like

no, but you could write your own:

def sum_even_keys(my_dictionary): 
    if not dictionary_valid(my_dictionary):
        raise ValueError("Invalid dictionary")
    return sum(val for num,val in my_dictionary.items() if num%2 ==0)

def dictionary_valid(the_dict):
    return all(type(key) is int and type(value) is int for key, value in the_dict.items())

print(sum_even_keys({2:4, 6: 8}))

this would be better, given each function now has one responsibility which makes it easier to test.

2 Likes

For future reference, once you have covered classes (second module after this one):

If you had a large project in which it was important to have this capability, the natural approach would be to create a class IntDict(dict) that inherits from dict, and which runs the validation as part of its __init__() method.

Any IntDict object would be forced to have only int type as key or value, but would otherwise exhibit normal dict behavior.

class IntDict(dict):    
    def __init__(self, v_dict):
        if not self.dictionary_valid(v_dict):
            raise ValueError("Invalid dictionary!")
        super().__init__(v_dict)         
        
    def __setitem__(self, key, value):
        if not type(key) is int and type(value) is int:
            raise ValueError("Invalid key or value!")
        super().__setitem__(key, value)
        
    def dictionary_valid(self, the_dict):
        return all(type(key) is int and type(value) is int for key, value in the_dict.items())        
    

a_dict = {3: 7, 4: 8}       # a conventional dictionary
# a_dict = {"a": 3, "b": 4} # will raise error at next step;  can't be an int_dict, since it has string keys.
int_dict = IntDict(a_dict)  # int_dict is now a dictionary accepting only int as key or value
# int_dict['b'] = 7    # raises error,  can't assign a string key
int_dict[5] = 9

print(int_dict)
print(int_dict[4])

Output:
{3: 7, 4: 8, 5: 9}
8