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:
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
CodePudding user response:
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.
CodePudding user response:
Given a file called yaml.yml
containing your supplied yaml data:
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}
You can parse the file with PyYAML in a standard way, which is covered in other answers such as this one. For example:
import yaml
with open("yaml.yml", "r") as stream:
try:
my_dict = yaml.safe_load(stream)
print(my_dict)
except yaml.YAMLError as exc:
print(exc)
Yields a print out of your YAML as a dict
:
$ python.exe yaml_so.py
{'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}}}
Creating a list of all data
items where flag == True
can be accomplished by using dict.items()
to iterate a view of the dictionary, for example:
for key, sub_dict in my_dict["data"].items():
if "flag" in sub_dict:
for sub_key, value in sub_dict.items():
if sub_key == "flag" and value:
print(f"sub_dict_entry: {key} -> key: {sub_key} -> value: {value}")
Yields:
sub_dict_entry: data1 -> key: flag -> value: True
sub_dict_entry: data2 -> key: flag -> value: True