Home > Back-end >  How to select a dictionary attribute based on another attribute's value in Python
How to select a dictionary attribute based on another attribute's value in Python

Time:08-10

I have a list (term_list) containing the following:

[
    {
        'taxonomy': 'type', 
        'href': 'https://example.com/1'
    }, {
        'taxonomy': 'status', 
        'href': 'https://example.com/2'
    }, {
        'taxonomy': 'feature', 
        'href': 'https://example.com/3'
    }
]

I need to select the href of the "taxonomy":"feature" BUT it's not guaranteed to be in the same order each time so I can't use list positioning.

How can I select the value of href depending on the value of taxonomy?

Any help would be appreciated. Thanks.

CodePudding user response:

If I understand you correctly, you can use list comprehensions:

term_list = [
    {
        'taxonomy': 'type',
        'href': 'https://example.com/1'
    }, {
        'taxonomy': 'status',
        'href': 'https://example.com/2'
    }, {
        'taxonomy': 'feature',
        'href': 'https://example.com/3'
    }
]

print([obj['href'] for obj in term_list if obj['taxonomy'] == 'feature'])

Ouptut:

['https://example.com/3']
  • Related