I have a list of random objects generated from a Model (querySet).
I intend to create a separate list of objects using some but not all of the values of the objects from the original list.
For instance,
people = [
{'name': 'John', 'age': 20, 'location': 'Lagos'},
{'name': 'Kate', 'age': 40, 'location': 'Athens'},
{'name': 'Mike', 'age': 30, 'location': 'Delhi'},
{'name': 'Ben', 'age': 48, 'location': 'New York'}
]
Here’s what I’ve tried:
my_own_list = []
my_obj = {}
for person in people:
my_obj['your_name'] = person['name']
my_obj['your_location'] = person['location']
my_own_list.append(my_obj)
However, my code created only one obj, repeatedly four times.
>Solution :
You have to create a new object for every new person:
my_own_list = []
for person in people:
my_obj = {}
my_obj['your_name'] = person['name']
my_obj['your_location'] = person['location']
my_own_list.append(my_obj)