getting part of dictionary in python

I have list of dictionaries

teachers = [

    {
        "id": 0,
        "goals": ["travel", "relocate", "study"],
    },

    {
        "id": 1,
        "goals": ["travel","study"],
    },
    {
        "id": 2,
        "goals": ["travel", "work", "study"],
    },
    {
        "id": 3,
        "goals": ["work", "relocate", "study"],
    }
]

I need to get part of dictionary where in "work" is in list in "goals" :

teachers = [
    {
        "id": 2,
        "goals": ["travel", "work", "study"],
    },

    {
        "id": 3,
        "goals": ["work", "relocate", "study"],
    }
]

How should I solve my problem?

Upvotes: 2

Views: 89

Answers (3)

ttimasdf
ttimasdf

Reputation: 1466

Use filter, the built-in function.

It returns an iterator, which minimized the overhead of list comprehension. If you only need a plain list as the result, just wrap it with a list()

>>> list(filter(lambda o:"work" in o["goals"], teachers))
[{'id': 2, 'goals': ['travel', 'work', 'study']}, {'id': 3, 'goals': ['work', 'relocate', 'study']}]

ref: https://docs.python.org/3/library/functions.html#filter

Upvotes: 0

Ernesto R. Bravo
Ernesto R. Bravo

Reputation: 1

Get the dictionary by pointing to it's index in the list.

print(teachers[3])

>>>{'id': 3, 'goals': ['work', 'relocate', 'study']}

Upvotes: -2

JL0PD
JL0PD

Reputation: 4518

Most compact solution is to use list comprehensions

teachers = [t for t in teachers if "work" in t["goals"]]

List comprehension in python, how to?

Upvotes: 4

Related Questions