Rookie
Rookie

Reputation: 429

Get Value of a key from List of dictionary

I have a list of dictionaries with 2 keys: 'name' & 'value'. I need to get the value of 'value' key if value of 'name' key is 'Subject'

Currently i'm iterating through each dict and checking the value of 'name' and getting the value of 'value'. Is there any improved way of doing this ?

items = [
            {
                "name": "From",
                "value": "[email protected]"
            },
            {
                "name": "Date",
                "value": "Tue, 8 Sep 2014 16:18:35 +0530"
            },
            {
                "name": "Subject",
                "value": "Test Subject"
            },
            {
                "name": "To",
                "value": "[email protected]"
            },
        ]

for item in items:
    if item.get('name') == 'Subject':
        print "Subject: " + item.get('value')

Upvotes: 2

Views: 197

Answers (3)

Ali SAID OMAR
Ali SAID OMAR

Reputation: 6792

As Jonas told, better for modify your structure because

from collections import defaultdict
it = [
            {
                "name": "From",
                "value": "[email protected]"
            },
            {
                "name": "Date",
                "value": "Tue, 8 Sep 2014 16:18:35 +0530"
            },
            {
                "name": "Subject",
                "value": "Test Subject"
            },
            {
                "name": "Subject",
                "value": "Test Subject 55"
            },
            {
                "name": "To",
                "value": "[email protected]"
            },
        ]


result = defaultdict(list)
# shorcut better to use for...
[result[item["name"]].append(item["value"]) for item in it]

print(result["Subject"])
['Test Subject', 'Test Subject 55']

Upvotes: 1

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

You could use next along with a generator filtering and converting the items.

>>> subject = next(field['value']
...                for field in items
...                if field['name'] == 'Subject')

Upvotes: 2

Jonas Byström
Jonas Byström

Reputation: 26129

You should transpose your data into a dict instead:

>>> d = dict([(e['name'],e['value']) for e in items])    # transpose

Or a slightly easier way as mentioned by Peter Wood in the comments:

>>> d = {e['name']: e['value'] for e in items}

Then just use the dict as normal:

>>> d['Subject']
'Test Subject'

Upvotes: 3

Related Questions