KeyError : 3 during dictionary call

Asked 2 years ago, Updated 2 years ago, 478 views

I'm currently studying formatting.

x = [10, 11, 12]
x1=[13,14,15]
"First element in the list = {0[0]}".format(x)

y = {"a": 10, "b": 11, "c": 12}
"A key value in dictionary = {0[a]}".format(y)
"A key value in dictionary = {1[a]},{0[2]}".format(x,y) #2nd of a, x of y 
#Note: 1[a] not 1[a']. KeyError male if 1['a']
"A key value in dictionary = {1[0]},{0[1]}".format(x,x1) #x1 0th order of x

y['a']#What's interesting is that you have to write "a" here, and if you just write "a", there's a Key Error...

I have two questions while studying.

The a-key value of the dictionary = {1[a]},{0[2]}".format(x,y) 

1. Why don't you put quotation marks on the dictionary's key, a?


x = [10, 11, 12]
x1=[13,14,15]
"First element in the list = {0[0]}".format(x)

y = {"a": 10, "b": 11, "c": 12}
"A key value in dictionary = {0[a]}".format(y)
"A key value in dictionary = {1[a]},{0[2]}".format(x,y) #2nd of a, x of y 
#Note: 1[a] not 1[a']. KeyError male if 1['a']
"A key value in dictionary = {1[0]},{0[1]}".format(x,x1) #x1 0th order of x

y[a]#What's interesting is that you have to write "a" here, and if you just write "a", there's a Key Error."

If you run the last line y['a'] as y[a] as follows

KeyError : 3

A appears. 2. I wonder why you don't put quotation marks here and why KeyError: 3 appears. I don't think there's anything related to 3, but I don't know why it's 3.

I'd really appreciate it if you could answer these two questions!

python dictionary keyerror

2022-10-12 01:00

1 Answers

str.format It seems to be a characteristic of the parser. For regular Python codes, the correct approach is to access the string key of the dictionary variable, such as y['a']. However, in str.format, you can pass the string key in the dictionary without giving any quotation marks to indicate the string. I didn't know either.

https://docs.python.org/ko/3/tutorial/inputoutput.html#the-string-format-method

However, in this case, confusion may occur when the dictionary's key is mixed with an integer string.

>>> d = { "33": 0, 33: 1 }
>>> "{0[33]}".format(d)
'1'
y[a]

If the KeyError:3 error occurred, the value of a would have been int 3. There must have been a code somewhere that specifies the value of the a variable as 3.


2022-10-12 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.