Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create Dict from a Python list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading