List comprehension on a list of dictionaries

Question:

I have a list of dictionaries like so:

[{'end': 34,
  'entity_group': 'ORG',
  'score': 0.99919325,
  'start': 0,
  'word': ' Community College Alabama'},
 {'end': 54,
  'entity_group': 'LOC',
  'score': 0.90115756,
  'start': 42,
  'word': ' Maxwell Blvd'},
 {'end': 66,
  'entity_group': 'LOC',
  'score': 0.9890175,
  'start': 56,
  'word': ' Montgomery'},
 {'end': 70,
  'entity_group': 'LOC',
  'score': 0.9988833,
  'start': 68,
  'word': ' AL'}]

I would like to extract values of word, but only the ones where 'entity_group': 'LOC'. So for the above example, that would be:

[' Maxwell Blvd', ' Montgomery', ' AL']

I have tried to do this:

[[item for item in d.items()] for d in a]

… but this does not yield what I want.

Asked By: AJW

||

Answers:

[d['word'] for d in a if d['entity_group'] == 'LOC']
Answered By: 吴慈霆

I’d go with get just to be safe in case the entity_group key is not present in your dict. If you use brackets to access that non-existing key you’ll get a KeyError.

  data = [{'end': 34,
  'entity_group': 'ORG',
  'score': 0.99919325,
  'start': 0,
  'word': ' Community College Alabama'},
 {'end': 54,
  'entity_group': 'LOC',
  'score': 0.90115756,
  'start': 42,
  'word': ' Maxwell Blvd'},
 {'end': 66,
  'entity_group': 'LOC',
  'score': 0.9890175,
  'start': 56,
  'word': ' Montgomery'},
 {'end': 70,
  'entity_group': 'LOC',
  'score': 0.9988833,
  'start': 68,
  'word': ' AL'}]

  words_for_loc_group = [item.get('word') for item in data if item.get('entity_group') == 'LOC']
Answered By: Gameplay

I think this works for you.

data = [
    {'entity_group': 'ORG', 'score': 0.99919325, 'word': ' Community College Alabama', 'start': 0, 'end': 34}, 
    {'entity_group': 'LOC', 'score': 0.90115756, 'word': ' Maxwell Blvd', 'start': 42, 'end': 54}, 
    {'entity_group': 'LOC', 'score': 0.9890175, 'word': ' Montgomery', 'start': 56, 'end': 66}, 
    {'entity_group': 'LOC', 'score': 0.9988833, 'word': ' AL', 'start': 68, 'end': 70}]



res = [i.get("word") for i in data if i.get("entity_group") == "LOC"]
Answered By: irasin
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.