close

How can I output blank value in python yaml file

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can I output blank value in python yaml file in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How can I output blank value in python yaml file?

  1. How can I output blank value in python yaml file?

    For None type to be read from python use null in yaml
    A YAML file test.yml like this
    foo: null bar: null

  2. output blank value in python yaml file

    For None type to be read from python use null in yaml
    A YAML file test.yml like this
    foo: null bar: null

Method 1

For None type to be read from python use null in yaml

A YAML file test.yml like this

foo: null
bar: null

will be read by python as

import yaml
test = yaml.load(open('./test.yml'))
print(test)

foo: None
bar: None

Method 2

If you load a YAML src

allow:

into Python you get None assigned to the key allow, that is the correct behaviour.

If you use ruamel.yaml (of which I am the author), and its RoundTripDumperNone is written as you want it (which is IMO the most readable, although not explicit):

import ruamel.yaml

print ruamel.yaml.dump(dict(allow=None), Dumper=ruamel.yaml.RoundTripDumper)

will give you:

allow:

You can also properly round-trip this:

import ruamel.yaml

yaml_src = """
allow:
key2: Hello  # some test

"""

data = ruamel.yaml.load(yaml_src, ruamel.yaml.RoundTripLoader)
print('#### 1')
print(data['allow'])
print('#### 2')
print(ruamel.yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper))

print('#### 3')

print(type(data))

to get as output:

#### 1
None
#### 2
allow:
key2: Hello  # some test


#### 3
<class 'ruamel.yaml.comments.CommentedMap'>

In the above, data is a subclass of ordereddict, which is necessary to keep track of the flowstyle of the input, handling comments attached to lines, order of the keys, etc..
Such a subclass can be created on the fly, but it is normally easier to start with some readable and well formatted YAML code (possible already saved on disc) and then update/extend the values.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read