Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select a dictionary attribute based on another attribute's value in Python

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help would be appreciated. Thanks.

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading