【发布时间】:2021-02-02 20:46:50
【问题描述】:
我有一个 python 字典,描述如下:
dict={
"Moli": {"Buy": 75, "Sell": 53, "Quantity": 300}
"Anna": "Buy": 55, "Sell": 83, "Quantity": 154}
"Bob": {"Buy": 25, "Sell": 33, "Quantity": 100}
"Annie": {"Buy": 74, "Sell": 83, "Quantity": 96}
}
我想选择或打印此嵌套字典的第一项的子值(即:"Buy": 75)。
如果我使用此代码:
print(trading_portfolio[(list(trading_portfolio.keys())[0])]["Buy"])
我收到这样的错误:
select first item from this nested dictionary
builtins.KeyError: "Buy"
【问题讨论】:
-
欢迎来到 SO!你的代码对我来说很好,但
next(iter(d.values()))["Buy"]似乎更可取。永远不要将变量命名为“dict”——它会覆盖内置变量。
标签: python python-3.x dictionary