#๐Ÿ”’ what is KeyError?

129 messages ยท Page 1 of 1 (latest)

lean pivot
#
lst = [[5, 12, 17, 21, 17], [20, 14, 11,7, 17]]
def get_numbers(lst):
    numdic = {}
    for l in lst:
        for n in l:
            if numdic[str(n)]==None:
                numdic[str(n)] = 1
            else:
                numdic[str(n)] += 1
        return numdic
print(get_numbers(lst).get("15",0))```


my intention is to calculate how many each unique numbers are in the list of list.

and printing out how many 15 is in the lst.
granite plazaBOT
#

@lean pivot

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

vocal yacht
#

You get KeyError if you try to access a dict entry which isn't there. Your numdict starts empty and the first thing you do is access an entry.

#

Probably this test: numdic[str(n)]==None
should be:

  • str(n) not in numdict
  • or numdict.get(str(n)) is None
#

BTW, why are you using str(n) fo the dict key instead of just n ? @lean pivot

lean pivot
#

Oh

#

Oh why did I do str(n) I guess

vocal yacht
#

Yes, that

lean pivot
#

numdic["key"]

vocal yacht
#

But why? dict keys do not need to be strings.

lean pivot
#

numdic[key]

#

I ve only seen {'a':1, 'b':2}

vocal yacht
#

Well you can use ints directly.

lean pivot
#

Can this be {1:1, 2:32} ??

vocal yacht
#

Yes

lean pivot
#

Oh didn't know.

#

I don't think that will affect my exam marks but

lean pivot
#

Should've use "is" for None

vocal yacht
#

Your KeyError came from this: numdic[str(n)]==None
That first evaluates numdic[str(n)], which asks for the entry with key str(n). That raises key error if the key is not there.

lean pivot
#

๐Ÿ˜ž

vocal yacht
#

numdict.get(str(n)) returns the value, or None if it isn't there.

lean pivot
#

I changed it to is

#

I still get the same error

vocal yacht
#

Like I said, numdic[str(n)] tries to access that entry, and it's not there.

#

You want numdic.get(str(n)) is None

lean pivot
#

None means not there ??

vocal yacht
#

None is used in Python for "no meaningful value".

#

The return value from dict.get is None if the key is not there.

#

The return value from numdict[key] is always the value, and it raises KeyError if the key is not there.

#

If you're probing for the key you can either use .get(key) and test the result for is None (key not there) or you can ask key not in numdict, which will be true if the key is not there

lean pivot
#

Ahhh only that line. I guess it won't be that much of bad marks for that ?????

vocal yacht
#

Well it does break the whole script. But it's a small error.

lean pivot
#

Null value

vocal yacht
#

No. None is what is returned from dict.get if there is no value in the dict

lean pivot
#

It was one of question in exam which doesn't allow me to use the interpreter

#

So I just used text page

vocal yacht
#

There are languages where they pretend the entry is there and serve up None (or null or whatever their not-a-value value is). But in Python, accessing a key which is not there gets a KeyError

vocal yacht
lean pivot
#

noice

vocal yacht
#

Well, I assume so anyway.

#

If you don't get to run and debug your script, the marking has to be more forgiving.

lean pivot
#

If I get more than 45 out of 60 . I will get the highest mark

#

It was like 6 of them were coding. The rest 32 was short answer

vocal yacht
#

See your last line went numdict.get(15,0)? That's written to cope with no 15s at all.

lean pivot
#

I checked I already lost 1 point in py what is x[3:-2]? , x = [4,6,8,10,12] I answered it is py type list and value [10]

void marsh
#

It would be []

lean pivot
void marsh
#

Your start/stop index are the same index, which returns nothing

lean pivot
#

I was confised

#

Because the first slice include 10

void marsh
#

it would be the same as trying to slice [3:3]

lean pivot
#

The behind slice exclude 10

void marsh
#

yes exactly

#

from 3 until 3 is empty

lean pivot
#

Why would somebody type [3:3]

void marsh
#

they wouldn't

#

but it's possible you're using variables to handle the slicing

vocal yacht
#

It's more to make sure you can figure out what it means.

lean pivot
#

Definitely lost 1 point there

#

So hope I didn't get more wrong than 14 points

#

But I did a bit complicated coding (rather too personal or obnoxious idk how to explain it ) on coding problems

#

Not the clean, "looks the right way" coding

#

One more question

#

What would you say .

What this will exactly print? 
print("cherry")```
void marsh
#

what did you put?

lean pivot
#

"cherry"

#

I included the double quote

void marsh
#

strings don't print with quotes

#

print("cherry") will print cherry

lean pivot
#

Yeah but

vocal yacht
#

print prints the value of the string, which is the text inside the quotes

lean pivot
#

On the blank thing

#

When I have to write the type and value

#

If the type is str

#

Value should be in " "

#

So I did "cherry"

void marsh
#

yes, that's how you create new strings

vocal yacht
#

The quote marks just mark out, to Python, where the string starts and ends

void marsh
#

but that's not how they display

vocal yacht
#

the value of the string itself is the text between

lean pivot
#

If the value is without the double quotes I'm screwed

#

Because in my memory

#

With type, value questions

#

I always had to do double quotes for str value

vocal yacht
#

If you go x="aa"

lean pivot
#

Let me check again

vocal yacht
#

then the value of the text is aa

#

but you need the quotes in the python code to mark that value out as a string

#

print(x) would just print aa

brittle sentinel
#

and a newline

vocal yacht
#

Well yes

lean pivot
#

So value "haha" would be alright

#

But the not the print("cherry") ?

void marsh
#

"haha" is a string literal

lean pivot
#

Let me check how I got in the example exam

#

Yeah they wanted double quotes for value

#

๐Ÿ˜ฎโ€๐Ÿ’จ

#

Thank my memory

void marsh
#

show the full question

#

you can use ' or " to create new strings

lean pivot
#

following expression

void marsh
#

yeah, it's not asking about output

#

but 's' should not be wrong

lean pivot
#

So "cherry" would be wrong I guess ?

void marsh
#

's' and "s" should both be right

void marsh
lean pivot
#

That's -2 or -3 total for now excluding coding mistakes

void marsh
#

the value is not always equal to what is printed

#

if they marked 's' wrong, I would seriously bring it up with your teacher

#

if anything, 's' is more correct because python uses ' interally for its literals

lean pivot
#

No I mean both "s" 's' is right

void marsh
#

!e

print(repr("s"))
granite plazaBOT
lean pivot
#

Print("cherry")

void marsh
lean pivot
#

Already -2 or -3 points

#

Well I've been lazy and was just worrying about the exam not keeping up with it since I was getting another exam because my laptop didn't work out on the normal exam date

#

I just used last 3 days for preparation which was ducky_skull ducky_skull

#

But it felt okay......

#

Thank you for the answer! I'll close this

#

!close

granite plazaBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.