0
How to separate the same value from a list in python ?
Okay ...let's say I have a json array list . And I want to separate the data by the same used id into another sub list. Then how it can be done Here is an example: list = [{'user_id': 12, 'status': 'good'}, {'user_id': 32, 'from': 'bd'}, {'user_id': 12, 'sataus': 'based'}] and output should be something like this way: output_list = [[{'user_id': 12, 'status': 'good'},{'user_id': 12, 'sataus': 'based'}] [{'user_id': 32, 'from': 'bd'}]]
13 Answers
+ 2
@all thank you very much for your help. I solved this issue.
Here is the solution
list = [{'user_id': 12, 'status': 'good'}, {'user_id': 32, 'from': 'bd'}, {'user_id': 12, 'sataus': 'based'}]
used_list = []
for i in list:
if i['user_id'] not in used_list:
#fetch all user data by user_id in django after that
used_list.append(i['user_id'])
+ 2
MD SAAD ,
as a base we need a list of all occurring user_id. this can be achieved by using a for loop. user_id should be stored in a list. to keep only unique values (and to remove duplicates), we can use a set, that will be converted to list finally
for the final step we have to iterate through the list of unique user_id. we can use a filter with a lambda function so that only dicts with the current user_id can pass.
each result will finally appended to a list that now is a list of lists, whereas the inner lists are holding the dictionaries.
the result will be:
[[{'user_id': 12, 'status': 'good'}, {'user_id': 12, 'sataus': 'based'}], [{'user_id': 32, 'from': 'bd'}]]
+ 1
MD SAAD ,
please give us a sample how the json looks like. also make a sample how the output should look like
+ 1
Here is an example:
from this list:
list = [{'user_id': 12, 'status': 'good'}, {'user_id': 32, 'from': 'bd'}, {'user_id': 12, 'sataus': 'based'}]
and should output this.
output_list = [[{'user_id': 12, 'status': 'good'},{'user_id': 12, 'sataus': 'based'}] [{'user_id': 32, 'from': 'bd'}]]
+ 1
Sorry, this one actually works.
print(sorted(list, key=lambda x: x['user_id']))
0
Dump the json file into a dictionary and you can access it however you want
0
This may be too complicated a solution, but you could try using sql on your data after turning it into tables. Then you can manipulate your data however you want.
0
a = []
for x in list:
for y in x.keys():
if y == âuser idâ:
if x[y] == 12:
a.append(x)
print(a)
0
madeline no bro ....I need this without being specified user_id == 12
0
Sorry! Do mean you want to seperate the list by user id?
0
Yes
0
Use the same code but add a for loop at the beginning, youll need the number of user ids. So if your user ids are 50 total the code would be...
a=[]
for idss in 50:
for x in list:
for y in list.keys():
if y == âuser_idâ:
if x[y] == idss:
a.append(x)
0
If you dont have the user ids, get them and then create the loops. Sorry, gl