通过字典和累积迭代

时间:2019-06-27 21:16:08

标签: python python-3.x dictionary

此刻,我正尝试在嵌套在字典中的字典中累积值以用于作业。

a = {
    "Tennis Balls": {
        "User Rating": 15,
        "Available Colors": 5,
        "Location": "Puppy Mart"
    }
}
b = {
    "Squeaky Toy": {
        "User Rating": 48,
        "Available Colors": 3,
        "Location": "Pooch Shop"
    }
}

c = {
    "Stick": {
        "User Rating": 32,
        "Available Colors": 4,
        "Location": "Pooch Shop"
    }
}
d = {
    "Old Shoe": {
        "User Rating": 13,
        "Available Colors": 2,
        "Location": "Puppy Mart"
    }
}
e = {
    "Stuffed Animal": {
        "User Rating": 14,
        "Available Colors": 7,
        "Location": "Dog Express"
    }
}
puppy_toys = {"Toys": [a, b, c, d, e]}

total_user_ratings = 0

for toy in puppy_toys["Toys"]:

    # insert your own code

    individual_user_rating = puppy_toys["Toys"][toy]["User Rating"]
    total_user_ratings += individual_user_rating

print(total_user_ratings)

我必须用单行代码填写# your line here,这将允许for循环迭代字典pypette_toys字典并提取位于“ Pooch Shop”的玩具的用户总评分,然后将总数存储在变量total_user_ratings中,但是下面显示的我的代码行似乎无效:

if["Location"] = "Pooch Shop":

感谢您的协助!

2 个答案:

答案 0 :(得分:0)

好吧,玩了一点之后,我想您想通过位置名称来获得用户评级的总和,因此,您实际上拥有一本带有列表的字典,如果我输入错了,请更正我,因此您只需要循环并采用这样的值:

a = {
    "Tennis Balls": {
        "User Rating": 15,
        "Available Colors": 5,
        "Location": "Puppy Mart"
    }
}
b = {
    "Squeaky Toy": {
        "User Rating": 48,
        "Available Colors": 3,
        "Location": "Pooch Shop"
    }
}

c = {
    "Stick": {
        "User Rating": 32,
        "Available Colors": 4,
        "Location": "Pooch Shop"
    }
}
d = {
    "Old Shoe": {
        "User Rating": 13,
        "Available Colors": 2,
        "Location": "Puppy Mart"
    }
}
e = {
    "Stuffed Animal": {
        "User Rating": 14,
        "Available Colors": 7,
        "Location": "Dog Express"
    }
}
puppy_toys = {"Toys": [a, b, c, d, e]}

total_user_ratings = 0

for toy in puppy_toys["Toys"]:
    shop = list(toy.values())[0]
    if (shop["Location"] == "Pooch Shop"):
        individual_user_rating = shop["User Rating"]
        total_user_ratings += individual_user_rating

print(total_user_ratings) 

答案 1 :(得分:0)

您的代码行有两个主要问题。让我们来看一下:

if["Location"] = "Pooch Shop":

首先,您尝试在两个表达式之间进行比较。这是在python中使用等于运算符==来完成的。一个=通常代表分配。

例如:

>>> a = 5
>>> print(a)
5
>>> print(a == 5)  # "is a equal to 5?"
True

第二个问题是if["Location"]

在Python中,方括号通常用作“获取程序”。一种访问对象内部元素(如列表或字典)的方法。

例如:

>>> a = ["x", "y", "z"]
>>> print(a[1])
y
>>> b = {"name": "Tomer", "age": 29}
>>> print(b["name"])
Tomer

因此,您希望["Location"]出现在某个对象之后。

在下一行代码中应有提示:

individual_user_rating = puppy_toys["Toys"][toy]["User Rating"]