Reputation: 45
I would like to print the rating result for different user in separate array. It can be solved by creating many arrays, but I didn't want to do so, because I have a lot of user in my Json file, so how can I do this programmatically?
python code
with open('/content/user_data.json') as f:
rating = []
js = json.load(f)
for a in js['Rating']:
for rate in a['rating']:
rating.append(rate['rating'])
print(rating)
output
['4', '2', '5', '1', '3', '5', '2', '5']
my expected result
['4', '2', '5']
['1', '3']
['5', '2', '5']
json file
{
"Rating" : [
{
"user" : "john",
"rating":[
{
"placename" : "Kingstreet Café",
"rating" : "4"
},
{
"placename" : "Royce Hotel",
"rating" : "2"
},
{
"placename" : "The Cabinet",
"rating" : "5"
}
]
},
{
"user" : "emily",
"rating":[
{
"placename" : "abc",
"rating" : "1"
},
{
"placename" : "def",
"rating" : "3"
}
]
},
{
"user" : "jack",
"rating":[
{
"placename" : "a",
"rating" : "5"
},
{
"placename" : "b",
"rating" : "2"
},
{
"placename" : "C",
"rating" : "5"
}
]
}
]
}
Upvotes: 0
Views: 73
Reputation: 10960
A simple one-liner
all_ratings = [list(map(lambda x: x['rating'], r['rating'])) for r in js['Rating']]
Explanation
all_ratings = [
list( # Converts map to list
map(lambda x: x['rating'], r['rating']) # Get attribute from list of dict
) for r in js['Rating'] # Iterate ratings
]
Upvotes: 0
Reputation: 31
Don't only append all ratings to one list, but create a list for every user:
with open('a.json') as f:
ratings = [] #to store ratings of all user
js = json.load(f)
for a in js['Rating']:
rating = [] #to store ratings of single user
for rate in a['rating']:
rating.append(rate['rating'])
ratings.append(rating)
print(ratings)
Upvotes: 2
Reputation: 21
You can just indent the print into the outer for loop and reset the array everytime.
for user in js["Rating"]:
temp_array = []
for rate in user["rating"]:
temp_array.append(rate["rating"])
print(temp_array)
Upvotes: 0