2

Let's say I have the following data structure:

SOME_LIST = [
  {
    'name': 'foo',
    'alternatives': [
      {
        'name': 'Foo'
      },
      {
        'name': 'foo'
      },
      {
        'name': 'fu
      }
    ]
  },
  {
    'name': 'bar',
    'alternatives': [
      {
        'name': 'Bar'
      },
      {
        'name': 'bar'
      },
      {
        'name': 'ba'
      }
    ]
  }
]

I want to produce a flattened list of the alternative "names" of the object as follows:

['foo', 'Foo', 'fu', ..., 'ba']

I've gone around the houses with various list comprehensions...and I just don't know how to do this elegantly.

I've tried:

[i['alternatives'] for i in SOME_LIST]

[*i['alternatives'] for i in SOME_LIST]
>>>SyntaxError: iterable unpacking cannot be used in comprehension

[alt['name'] for alt in [i['alternatives'] for i in SOME_LIST]]
>>>TypeError: list indices must be integers or slices, not str
halfer
  • 19,824
  • 17
  • 99
  • 186
Micheal J. Roberts
  • 3,735
  • 4
  • 37
  • 76
  • 2
    Please update your question with some of the `around the houses` code you have tried. – quamrana May 07 '21 at 16:20
  • @quamrana Duly noted, and updated. – Micheal J. Roberts May 07 '21 at 16:24
  • Your starting data structure is pretty bizarre. But [shrug] sometimes that's what you get to work with. It's a little unclear whether you want the original `SOME_LIST[i]['name']` included in the final list too, although in this case those also appear in the `'alternatives'` anyway. – Joffan May 07 '21 at 16:27

1 Answers1

3

You can use a nested list comprehension:

result = [j['name'] for i in SOME_LIST for j in i['alternatives']]

Output:

['Foo', 'foo', 'fu', 'Bar', 'bar', 'ba']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102