Skip to content

Instantly share code, notes, and snippets.

@jemoster
Last active April 8, 2017 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jemoster/b16bb659c9474507d6e1f3f64ff52ac2 to your computer and use it in GitHub Desktop.
Save jemoster/b16bb659c9474507d6e1f3f64ff52ac2 to your computer and use it in GitHub Desktop.
Python dictionary in-line list comprehensions
import json
from typing import List
from uuid import uuid4
# Sample classes for building our data structure
class Inventory:
def __init__(self, name: str, express: bool=False):
self.name = name
self.express = express
self.id = str(uuid4())
class Order:
def __init__(self, first: str, last: str, items: List[Inventory]):
self.first = first
self.last = last
self.items = items
self.id = str(uuid4())
# Build a sample data set
orders = [
Order('John', 'Smith', [
Inventory('Apple', True),
Inventory('Sausage'),
Inventory('Eggs')
]),
Order('Hildred', 'Spencer', ()),
Order('Candice', 'Silvester', [
Inventory('Ham', True),
Inventory('Potato', True)
]),
]
# Construct a dictionary representing the structure
# Using in-line list comprehensions lets us build the dictionary without needing to
# declare the lists ahead of time. The final code lets us see the entire dictionary
# structure cleanly in one place!
status = {
'orders': [
{
'name': ' '.join((order.first, order.last)),
'id': order.id,
'items': [
{
'name': inventory.name,
'id': inventory.id,
}
for inventory in order.items if inventory.express # Nested list comprehension with conditional statement
]
}
for order in orders # Simple list comprehension to iterate over the orders in the list
]
}
print(json.dumps(status, indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment