This is my data structure. I have 3000 instances of ‘product’ within the ‘clothes list’. Each contains another list of dictionaries that stores the reviews.
JavaScript
x
26
26
1
clothes_list =
2
[
3
{
4
"ID": "1000201",
5
"Name": "Clothes Name",
6
"Price": 24.1,
7
"Category": "Trousers"
8
"Reviews": [{'User': 'username1200', 'Review': 'some review', 'Score': 2}
9
{'User': 'username341', 'Review': 'Some review 2' , 'Score': 4}
10
{'User': 'username34841', 'Review': 'Some review 3' , 'Score': 2}
11
]
12
},
13
14
{
15
"ID": "1003801",
16
"Name": "Clothes Name",
17
"Price": 29.1,
18
"Category": "Trousers"
19
"Reviews": [{'User': 'username1200', 'Review': 'some review', 'Score': 2}
20
{'User': 'username341', 'Review': 'Some review 4' , 'Score': 7}
21
{'User': 'username34841', 'Review': 'Some review 5' , 'Score': 4}
22
]
23
},
24
25
]
26
I am attempting to iterate through all the reviews in the dictionary and return all the reviews written by a particular username.
My Two attempts below output the same error.
JavaScript
1
3
1
username = "username341"
2
reviews = next((review for review in clothess_list if review["Reviews"]["User"] == username))]
3
JavaScript
1
2
1
values = [a_dict["Reviews"][username] for a_dict in clothes_list]
2
The Error
TypeError: list indices must be integers or slices, not str
Target Output
JavaScript
1
3
1
{'User': 'username341', 'Review': 'Some review 2' , 'Score': 4},
2
{'User': 'username341', 'Review': 'Some review 4' , 'Score': 7}
3
Advertisement
Answer
Your logic review["Reviews"]["User"]
can’t be iterable because Reviews
is a list of dictionaries. You can’t directly call dictionary without putting any index of list.
JavaScript
1
5
1
username = "username341"
2
reviews=next( user for review in clothes_list for user in review['Reviews'] if user['User']==username)
3
4
print(reviews)
5
Output
JavaScript
1
2
1
{'User': 'username341', 'Review': 'Some review 2', 'Score': 4}
2