[英]Nested Dictionary Syntax
I am writing program code to record the stock in the nested list to a dictionary using the code as key (eg, '3AB'
) and the value is a list containing the stock information without the code (eg, ["Telcom", "12/07/2018", 1.55, 3000]
). 我正在编写程序代码,以使用代码作为键(例如
'3AB'
)将嵌套列表中的股票记录到字典中,并且值是一个包含不带代码的股票信息的列表(例如["Telcom", "12/07/2018", 1.55, 3000]
)。 My program code must also be able to access the elements in the nested list. 我的程序代码还必须能够访问嵌套列表中的元素。
However, when I run my code, it keeps on hitting syntax error. 但是,当我运行我的代码时,它不断出现语法错误。 Can I check what is wrong with my code?
我可以检查我的代码有什么问题吗?
stock = {
3AB: {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': '1.55', 'Volume':'3000'},
S12: {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': '3.25', 'Volume': '2000'},
AE1: {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': '1.45', 'Volume': '5000'}
}
print(stock[3AB]['Name'])
print(stock[S12]['Name'])
print(stock[AE1]['Name'])
Use this 用这个
stock = {
'3AB': {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': '1.55', 'Volume':'3000'},
'S12': {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': '3.25', 'Volume': '2000'},
'AE1': {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': '1.45', 'Volume': '5000'}
}
print(stock['3AB']['Name'])
print(stock['S12']['Name'])
print(stock['AE1']['Name'])
it throws error because in your code look at 3AB as a variable that it cannot found so you need pass it in '' as string 它将引发错误,因为在您的代码中将3AB视为找不到的变量,因此您需要将其作为字符串传递给''
键必须是可哈希的。您的键3AB必须是字符串。更改为“ 3AB”,其他键与3AB相同。
You got the error: 您收到错误:
SyntaxError: invalid syntax
SyntaxError:语法无效
because your dictionary was unhashable. 因为您的字典无法散列。 ie Invalid literal key
3AB
, the correct syntax, being '3AB'
: 即无效的文字键
3AB
,正确的语法为'3AB'
:
stock = {
'3AB': {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': '1.55', 'Volume':'3000'},
'S12': {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': '3.25', 'Volume': '2000'},
'AE1': {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': '1.45', 'Volume': '5000'}
}
print(stock['3AB']['Name'])
print(stock['S12']['Name'])
print(stock['AE1']['Name'])
OUTPUT: 输出:
Telcom
S&P
A ENG
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.