How to create Dict from a Python list

Question:

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.

Asked By: Baanu

||

Answers:

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)
Answered By: Runinho

Your getting the same entry because you predefine the dict you put into a list and overwrite the same dict – so each dict in your list references to the same dict in memory and hence they’re all the same

you could use a list comprehension like so :

my_own_list = [{"a": person["name"], "b": person["location"]} for person in people]
Answered By: Chris

please declare my_obj inside the for loop . it will work .

Answered By: rohini m

Your code corrected

my_own_list = []

for person in people:
    # every time you create a new dictionary
    my_obj = {}
    my_obj['your_name'] = person['name']
    my_obj['your_location'] = person['location']
    my_own_list.append(my_obj)

One-liner that uses list and dict comprehension 🙂

[{k:v for k,v in p.items() if k in ['name', 'location']} for p in people]
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.