Rounak Modak
Rounak Modak

Reputation: 155

How to filter an ordered dictionary in Python using Django?

Actully I am new to Python.Working with Python,Django and Mysql. I was trying to filter some data from an ordered dictionary which i received while fetching data from mySQL database.The entire data is there in a variable. But I want to store some of it in another variable...

This is my view.py file...

all_dataobj=fetchdata.objects.all()
pserializer=fetchdataSerializers(all_dataobj,many=True)
p = pserializer.data
print(p)

And I am getting data like this...

[OrderedDict([('id', 1), ('first_name', 'raunak'), ('middle_name', 'yy'), ('last_name', 'ron')]),
 OrderedDict([('id', 2), ('first_name', 'josh'), ('middle_name', 'yy'), ('last_name', 'mod')]),
 OrderedDict([('id', 3), ('first_name', 'david'), ('middle_name', 'yy'), ('last_name', 'cop')]),
 OrderedDict([('id', 4), ('first_name', 'bob'), ('middle_name', 'zj'), ('last_name', 'go')])]

Now I want to filtre this ordered dictionary and store data of id 1 and 2 only in a variable. So, if I print the result variable it should look like this...

[OrderedDict([('id', 1), ('first_name', 'raunak'), ('middle_name', 'yy'), ('last_name', 'ron')]),
 OrderedDict([('id', 2), ('first_name', 'josh'), ('middle_name', 'yy'), ('last_name', 'mod')])]

Please help me...i am stuck for very long...How can I get so??

Upvotes: 1

Views: 1277

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

You can iterate over the list and choose only the id's you want

ids_to_get = [1, 2]
#Loop over the list and select only the id's you want
res = [item for item in li if item.get('id') in ids_to_get]
print(res)

The output will be

[OrderedDict([('id', 1), ('first_name', 'raunak'), ('middle_name', 'yy'), ('last_name', 'ron')]),
 OrderedDict([('id', 2), ('first_name', 'josh'), ('middle_name', 'yy'), ('last_name', 'mod')])]

If a range of id's need to be looked into, say 1 to 100 inclusive of both limits, a conditional statement can be used

res = [item for item in li if 1 <= item.get('id') <= 100]

Upvotes: 1

Related Questions