简体   繁体   中英

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] ). 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相同。

You got the error:

SyntaxError: invalid syntax

because your dictionary was unhashable. ie Invalid literal key 3AB , the correct syntax, being '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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM