【问题标题】:Python nested dictionary problem with accessPython嵌套字典访问问题
【发布时间】:2022-01-12 21:02:45
【问题描述】:

这是我的字典。

data_item =   {
            "item": [
                {
                    "ID": 141232,
                    "cost": 83500,
                    "quantity": 1
                },
        
                {
                    "ID": 45330,
                    "cost": 84600,
                    "quantity": 15
                },
                {
                    "ID": 31315,
                    "cost": 84800,
                    "quantity": 5
                },
                {
                    "ID": 50497,
                    "cost": 84800,
                    "quantity": 3
                }
            ]
        }

我一直在尝试访问“成本”...

我尝试了类似的变体

for k,v in data_item['item']:
    if ['cost'] <= 84000:
        price = ['cost']
        print(f"Price is ${price}!")

和

for ['cost'] in data_item['item'].items:
    if ['cost'] <= 84000:
        price = ['cost']
        print(f"Price is ${price}!")

以及两者之间的大量变化...... 我收到类似的错误 AttributeError:“列表”对象没有属性“项目” ValueError:要解压的值太多(预期为 2)

我正准备放弃,但我想先在这里问。 如何访问值“成本”以便我可以在代码中进一步使用它?

【问题讨论】:

  • data_item['item'] 是一个列表
  • ['cost'] 是一个列表,不访问字典的cost 元素。

标签: python dictionary


【解决方案1】:

正确的方法是

for item in data_item["item"]:
    price = item["cose"]
    if price<= 8400:
        print(f"Price is {price}")

关键是要了解代码中的各种数据类型。 data_item 是一个字典,你可以通过键访问它。您使用语法data_item["item"] 获得与键'item' 关联的列表(注意引号)。然后你遍历列表。列表的元素又是字典,您可以通过键访问它们。这就是你在 for 循环中使用 item["cost"] 的地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 2021-11-07
    • 2017-01-20
    • 2018-02-07
    相关资源
    最近更新 更多