-3

I want to filter even and odd values from a dictionary. I tried to add these even and odd values to lists but I keep getting empty output, why? My code is like this:

def Split(Dic1):
    even = [ele for ele in Dic1.values() if ele is 2 ==0]
    odd  = [ele for ele in Dic1.values() if ele is 2 !=0]
    print("Even lists:", even)
    print("Odd lists:", odd)

 Dic1  = {"N1": [1, 3, 7, 6, 10],
    "N2": [2, 3, 9, 10, 21, 36],
    "N3": [4, 6, 5, 12, 24, 35],
    "N4": [0, 3, 14, 15, 16, 18]
  }
  Split(Dic1)

output:

Even lists: []
Odd lists: []
tripleee
  • 175,061
  • 34
  • 275
  • 318
Tbb
  • 13
  • 2

1 Answers1

0

ele is 2 == 0 is really not at all the correct way to express this. The is operator checks whether two variables refer to the same object; comparing this truth value (True or False) to 0 is basically if False == False but that's obviously not what you are trying to check for.

The operator to check whether something is divisible evenly is called modulo and in Python it is spelled %.

Traversing the input list twice seems inelegant; you probably should just loop once, and pick out which new list to copy each value to.

Your function should not attempt to modify global variables. Instead, make it return two new lists, and have the caller decide what to do with the result (here, print it).

Your input dictionary's values() are not numbers so you can't use them directly in a loop. Either split out individual values for each key, or change the function to expect a list of lists from values().

Probably don't use Proper Case for function names; the Python convention is to capitalize class names, but use snake_case for regular functions and variables.

def even_odd_split(Dic1):
    even = []
    odd = []
    for sublist in Dic1.values():
        for ele in sublist:
            if ele % 2 == 0:
                even.append(ele)
            else:
                odd.append(ele)
    return even, odd

print('Even items: %s\nOdd items%s' % even_odd_split(Dic1))

Perhaps notice that % is also - somewhat confusingly - a formatting operator when its first argument is a string. This is an example of operator overloading; though modern Python would perhaps prefer that you use .format() or an f-string here.

tripleee
  • 175,061
  • 34
  • 275
  • 318