Skip to content
Advertisement

filter even and odd values from a dictionary and add these even and odd values to lists and write them to a txt file

code:

def even_odd_split(Dic1):
    even = []
    odd =  []
    for sublist in Dic1.values():
        for x in sublist:
            if x % 2 == 0:
            even.append(x)
            else:
            odd.append(x)
    return even, 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]
     }

     print('Even items: %snOdd items%s' % even_odd_split(Dic1))

     with open("odd.txt","w") as f:
             f.write(str(odd))

     with open("even.txt","w") as f:
             f.write(str(even))

error: name ‘odd’ is not defined

Is it not found because it is empty in the lists but I add even and odd number. I do not understand why you gave such an error.How can i fix error?

Advertisement

Answer

Variables have a scope. If they are in a method, the variables are gone when the method is finished. That’s why you return stuff.

At the place where you call the method, you can then assign the results of the method to new variables.

Since you return a tuple, you can have 2 variables at the assignment:

x, y = even_odd_split(Dic1)

Or, if you like to have the same names again

even, odd = even_odd_split(Dic1)

Here’s the full code. Read it carefully and try to understand what it is all about with the names. Note that they are different inside and outside the method.

def even_odd_split(numbers):
    even_numbers = []
    odd_numbers = []
    for sublist in numbers.values():
        for x in sublist:
            if x % 2 == 0:
                even_numbers.append(x)
            else:
                odd_numbers.append(x)
    return even_numbers, odd_numbers


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]
        }

even, odd = even_odd_split(Dic1)
print(f'Even items: {even}nOdd items: {odd}')

with open("odd.txt", "w") as f:
    f.write(str(odd))

with open("even.txt", "w") as f:
    f.write(str(even))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement