List of Dictionaries

Use Case: a List of Dictionaries, and want to find the dictionary with a specific attribute.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
labels = [
  label_annotations {
    mid: "/m/0d9wj"
    description: "Urban design"
    score: 0.7931631207466125
    topicality: 0.7931631207466125
  },
  label_annotations {
    mid: "/m/025s3q0"
    description: "Landscape"
    score: 0.621519923210144
    topicality: 0.621519923210144
  },
  label_annotations {
    mid: "/m/02ky346"
    description: "Engineering"
    score: 0.6075770258903503
    topicality: 0.6075770258903503
  }
]

The following returns a List with the Dict containing the attribute searched

1
2
3
4
landscape_label = list(
    filter(lambda label: label.description == "Landscape", labels)
)
assert len(landscape_label) > 0

The following returns just the Dict

1
2
3
4
5
landscape_label = next(
  (item for item in labels if item.description == "Landscape"),
  None
)
assert(landscape_label.description == 'Landscape')

Reference: https://stackoverflow.com/questions/8653516/python-list-of-dictionaries-search


comments powered by Disqus