T. L T. L - 10 days ago 4
Python Question

Error: global name 'odd' is not defined when creating dictionary

I am trying to create a function that returns a dictionary with keys "even" and "odd" and an array of the even & odd values from a range. Here's my codes:

def dictionary_even_odd(x, y):
d = {}
for i in range(x, y+1):
if i % 2 == 0:
d[even].append(i)
else:
d[odd].append(i)
return d


However, I get an error message "NameError: global name 'odd' is not defined".

Can anyone points out how to fix these codes? I would really appreciate it!!

Edit:

Thanks everyone for the suggestions! It worked after I defined the key names at the beginning.

Answer

you need to use defaultdict from collections, and need key of string 'even' and 'odd'

import collections 
def dictionary_even_odd(x, y):
    d = collections.defaultdict(list)
    for i in range(x, y+1):
        if i % 2 == 0:
            d['even'].append(i)
        else:
            d['odd'].append(i)
    return d
Comments