Juicy
Juicy

Reputation: 12530

Get dictionary with key/value in a list of dictionaries

I have a list of dictionaries that looks like this:

[
    {
        "name": "hello",
        "value": "world"
    },
    {
        "name": "foo",
        "value": "bar"
    }
]

What's the pythonic way of fetching the dictionary where name = "foo" from a list of dictionaries?

Upvotes: 1

Views: 59

Answers (2)

Chandella07
Chandella07

Reputation: 2117

Try this simple example.

data = [
    {
        "name": "hello",
        "value": "world"
    },
    {
        "name": "foo",
        "value": "bar"
    }
  ]


for item in data:
    if item['name'] == 'foo':
        print(item)

Output:

{'name': 'foo', 'value': 'bar'}

Upvotes: 0

blhsing
blhsing

Reputation: 107124

Assuming your list of dicts is stored as variable l, you can use next() with a generator expression like this, which returns the first dict whose name key is foo:

next(d for d in l if d['name'] == 'foo')

This will otherwise raise StopIteration if there is no dict in l with a name key that equals foo.

Upvotes: 4

Related Questions