Name error


def find_key(dic,value):

    dic = {1:'apple',2:'orange',3:'grapes',4:'mangoes'}

    for key,value in dic.items:

        print (key,value)

    return key

print (find_key(dic,'apple'))

I am getting an error in the line of the print statement that dic is not defined when l have defined it immediately after creating the function

A NameError does not mean a name is not defined anywhere instead it means that name cannot be found in the current namespace or scope.

You should also be careful of the difference between func and func().

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS C:\Users\simmy.vscode> & C:/Users/simmy/AppData/Local/Programs/Python/Python39-32/python.exe c:/Users/simmy/.vscode/test4.py
Traceback (most recent call last):
File “c:\Users\simmy.vscode\test4.py”, line 8, in
print (find_key(dic,‘apple’))
NameError: name ‘dic’ is not defined
PS C:\Users\simmy.vscode>

Yes, that is the same error. You seem to have missed some fundamentals of working with functions, I’d highly suggest recapping anything you’ve learnt about them.

def func():
    x = 4


print(x)

This snippet alone will inevitably throw an error. Functions have their own scope.

Here there is no return statement and you are not calling the function, in my case l have that

Return does NOT call the function. It only operates when the function is called to return something form the function back to the caller. I’d really suggest learning functions from the ground up, they are essential to Python, it’s not something you want to gloss over. You’re making your own life harder by skipping the fundamentals.

2 Likes

not calling, l meant this

You really should consider taking @tgrtim’s advice, and review functions from the ground up. Your code contains the same error that @tgrtim showed you in his example. Something defined inside a function only exists inside the function. You are trying to pass as an argument an object, in this case a dictionary, that has not been defined in the scope of your function call. This is very rudimentary knowledge that you seem to have missed somewhere along the way. As @tgrtim said, you are making things more difficult for yourself by plowing ahead without an adequate understanding of basic fundamentals.

2 Likes

ok, l will recap, or is it maybe l don’t know how to work with dictionary and functions

1 Like

The issues in your OP for this topic are mainly related to functions and scope. A thorough review of both would be beneficial in my opinion. Good luck, and happy coding!

4 Likes

dic = {1:'apple',2:'orange',3:'grapes',4:'mangoes'}

def find_key(dic,value):

    #global dic

    #dic = {1:'apple',2:'orange',3:'grapes',4:'mangoes'}

    

    for key,value in dic.items():

        print (key,value)

    return value

print (find_key(dic,'apple'))

This works however l am getting mangoes, printed out twice, I don’t know why?

If l uncomment this part

and comment this,it doesn’t run and as per what l have seen about this topic, its supposed to work

So l have this


#dic = {1:'apple',2:'orange',3:'grapes',4:'mangoes'}

def find_key(dic,value):

    global dic

    dic = {1:'apple',2:'orange',3:'grapes',4:'mangoes'}

    

    for key,value in dic.items():

        print (key,value)

    return value

print (find_key(dic,'apple'))

You can’t pass dic as an argument if dic isn’t defined in the same scope as the function call. In your last code snippet, you commented out the definition of dic that is in the same scope as the function call. You should just delete the definition of dic that is inside the function. You also don’t need the global dic. Global variables should almost never be used, and there is no need to use it with a dictionary.

If you go back to the code you had one post up (removing the unnecessary code):

This code will run without error, but probably isn’t doing what you intended. Judging from the name of the function, I would assume that the function is supposed to take a dictionary and a value as parameters, and return the dictionary key that is associated with the value passed. Your function is iterating through the dictionary, printing every key: value pair, and then returning the last value to the caller which is a print function, so the final value mango gets printed at the end (this explains why you see mango twice.)

You have a for...in loop to iterate through the dictionary, but you don’t have any logic to determine when you’ve found the value you are looking for (in this case apple). When you find it, you should exit the loop and the function by returning the key that is associated with the value. This is all assumption on my part since you haven’t shared links to any assignment or specifically stated what the function is supposed to do.

2 Likes

I guess I’m not following why you’d need to write the function at all. If you just want to find the key from the value in the dictionary, why not just use a list comprehension?

dic = {1:'apple',2:'orange',3:'grapes',4:'mangoes'}

[key for key, fruit in fruits.items() if fruit == 'apple']

There’s a whole module on dictionaries in the Python (and DS path) course.

1 Like

I would guess that it’s an exercise or lesson requirement from somewhere. :man_shrugging:

Yes it was an exercise, next time l will post it, and yes also my logic was wrong, but l saw how it was solved in the solution

Thanks

1 Like

This is true too, it was a requirement

Exercise 136: Reverse Lookup
(Solved, 45 Lines)
Write a function named reverseLookup that finds all of the keys in a dictionary
that map to a specific value. The function will take the dictionary and the value to
search for as its only parameters. It will return a (possibly empty) list of keys from
the dictionary that map to the provided value.
Include a main program that demonstrates the reverseLookup function as part
of your solution to this exercise. Your program should create a dictionary and then
show that the reverseLookup function works correctly when it returns multiple
keys, a single key, and no keys. Ensure that your main program only runs when
the file containing your solution to this exercise has not been imported into another
program

Solution: