8.1. Comprehensions Nesting

8.1.1. Nested Comprehensions

DATA = [{'lastname': 'Watney'},
        {'firstname': 'Melissa', 'lastname': 'Lewis'},
        {'firstname': 'Rick'},
        {'firstname': 'Beth', 'lastname': 'Johanssen'},
        {'firstname': 'Chris', 'lastname': 'Beck', 'born': 1961}]

 fieldnames = set(key
     for row in DATA
         for key in row.keys()
 )

 print(fieldnames)
 # {'born', 'lastname', 'firstname'}
DATA = [{'lastname': 'Watney'},
        {'firstname': 'Melissa', 'lastname': 'Lewis'},
        {'firstname': 'Rick'},
        {'firstname': 'Beth', 'lastname': 'Johanssen'},
        {'firstname': 'Chris', 'lastname': 'Beck', 'born': 1961}]

 fieldnames = set()
 fieldnames.update(key
     for row in DATA
         for key in row.keys()
 )

 print(fieldnames)
 # {'born', 'lastname', 'firstname'}
DATA = [{'lastname': 'Watney'},
        {'firstname': 'Melissa', 'lastname': 'Lewis'},
        {'firstname': 'Rick'},
        {'firstname': 'Beth', 'lastname': 'Johanssen'},
        {'firstname': 'Chris', 'lastname': 'Beck', 'born': 1961}]

 fieldnames = set()
 fieldnames.update(key for row in DATA for key in row.keys())

 print(fieldnames)
 # {'born', 'lastname', 'firstname'}

8.1.2. Generator comprehensions

DATA = [{'lastname': 'Watney'},
        {'firstname': 'Melissa', 'lastname': 'Lewis'},
        {'firstname': 'Rick'},
        {'firstname': 'Beth', 'lastname': 'Johanssen'},
        {'firstname': 'Chris', 'lastname': 'Beck', 'born': 1961}]

 fieldnames = set()

 fieldnames.add(key
     for row in DATA
         for key in row.keys()
 )

 print(fieldnames)
 # {<generator object <genexpr> at 0x1179a0a50>}