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.
clothes_list =
[
{
"ID": "1000201",
"Name": "Clothes Name",
"Price": 24.1,
"Category": "Trousers"
"Reviews": [{'User': 'username1200', 'Review': 'some review', 'Score': 2}
{'User': 'username341', 'Review': 'Some review 2' , 'Score': 4}
{'User': 'username34841', 'Review': 'Some review 3' , 'Score': 2}
]
},
{
"ID": "1003801",
"Name": "Clothes Name",
"Price": 29.1,
"Category": "Trousers"
"Reviews": [{'User': 'username1200', 'Review': 'some review', 'Score': 2}
{'User': 'username341', 'Review': 'Some review 4' , 'Score': 7}
{'User': 'username34841', 'Review': 'Some review 5' , 'Score': 4}
]
},
]
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.
username = "username341"
reviews = next((review for review in clothess_list if review["Reviews"]["User"] == username))]
values = [a_dict["Reviews"][username] for a_dict in clothes_list]
The Error
TypeError: list indices must be integers or slices, not str
Target Output
{'User': 'username341', 'Review': 'Some review 2' , 'Score': 4},
{'User': 'username341', 'Review': 'Some review 4' , 'Score': 7}
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.
username = "username341"
reviews=next( user for review in clothes_list for user in review['Reviews'] if user['User']==username)
print(reviews)
Output
{'User': 'username341', 'Review': 'Some review 2', 'Score': 4}