Skip to main content

Command Palette

Search for a command to run...

List of Dictionary Transformation in Python

Published
1 min read
List of Dictionary Transformation in Python

Python have this feature called list comprehension, it allow to create new list using a more concise syntax than for loop.

Without list comprehension:

num = [1,2,3,4,5]
squared = []
for n in num:
    squared.append(n**2)
print(squared) # [1,4,9,16,25]

With list comprehension:

num = [1,2,3,4,5]
squared = [n**2 for n in num]
print(squared) # [1,4,9,16,25]

the syntax is as followed:

[expression for item in iterable if condition]

the condition is optional

the thing is, expression mean anything that can return value, so, this is possible

new_item = [transform_value(item) for item in some_iterable]

so, one application for this is to transform list of dictionary into class, useful for transforming database result into pydantic object

from pydantic import BaseModel

class TodoResponse(BaseModel):
    id: int
    content: str
    done: bool

todo_db = [
    {'id': 1, 'content': 'wash dish', 'done': False},
    {'id': 2, 'content': 'clean window', 'done': False},
    {'id': 3, 'content': 'do laundry', 'done': True}
]

todo_response = [TodoResponse(
    id=todo['id'], 
    content=todo['content'], 
    done=todo['done']
) for todo in todo_db]

Snippets and reference

https://realpython.com/ref/glossary/comprehension/

https://realpython.com/ref/glossary/collection/

https://realpython.com/list-comprehension-python/

https://www.reddit.com/r/learnpython/comments/1e5eqv5/can_anyone_quickly_explain_the_basics_of_list/