【问题标题】:How to select first item's sub-value from a nested dictionary? [duplicate]如何从嵌套字典中选择第一项的子值? [复制]
【发布时间】: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


【解决方案1】:

您可以尝试此代码,如果它不符合您的期望,请向我发送您的确切查询......

trading_portfolio={
  "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}
 }
print(trading_portfolio[(list(trading_portfolio.keys())[0])]["Buy"])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-11
    • 2021-03-09
    • 2018-04-12
    • 1970-01-01
    • 2020-01-26
    • 2020-12-21
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多