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

Get specific data from dictionary generated from yaml

I have a yaml that I need to process with a python script, the yaml is something like this:

user: john
description: Blablabla
version: 1
data: 
 data1: {type : bool, default: 0, flag: True}
 data2: {type : bool, default: 0, flag: True}
 data3: {type : float, default: 0, flag: false}

I need a list the the names of all the data that for example are bools or float, or all the ones where "flag" equals True or False, but I’m having difficulties moving around the list and getting what I need.

I’ve tried something like this:

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

   x = raw_data.items()
    for i in range(len(x['data'])):
        if (x['data'][i]).get('type') == "bool":
            print(x['data'][i])

But then I get an error: TypeError: ‘dict_items’ object is not subscriptable

>Solution :

You can use the type() function to check the type of an object in Python. In this case, x['data'] returns a dictionary, so you can use the items() method to get the items in the dictionary and then iterate over them to check their values. Here’s an example of how you can do this:

# Get the items in the 'data' dictionary
data_items = x['data'].items()

# Iterate over the items in the dictionary
for key, value in data_items:
    # Check the type of the value
    if type(value) == bool:
        print(key)

In this code, key will be the name of the data (e.g. data1, data2, etc.), and value will be the dictionary containing the type, default value, and flag. You can then check the values in this dictionary using the get() method, as you did in your code.

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