• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Convert Python Dictionary to YAML

Convert Python Dictionary to YAML

Author: Aditya Raj
Last Updated: February 10, 2023

YAML is a data serialization format used to store and transmit data in a human-readable and easy-to-write format. We can store and transmit python objects using YAML format. In this article, we will discuss how to convert a python dictionary to YAML format.

Table of Contents
  1. What is the YAML Format?
  2. Python Dictionary to a YAML String
  3. Convert Dictionary to YAML File in Python
  4. Conclusion

What is the YAML Format?

YAML is a data format commonly used for configuration files, data exchange between systems, and in modern application development as an alternative to JSON and XML.

YAML’s syntax is simple, clean, and readable. It uses indentation to define the structure of the data, making it easy to see the relationships between different elements. The syntax is also very flexible, allowing for the representation of simple scalar values (such as strings, numbers, and booleans) as well as complex data structures, such as lists and dictionaries.

Following is an example of a YAML file.

employee:
  name: John Doe
  age: 35
  job:
    title: Software Engineer
    department: IT
    years_of_experience: 10
  address:
    street: 123 Main St.
    city: San Francisco
    state: CA
    zip: 94102

The above YAML file describes information about an employee. 

  • The top-level key employee maps to an object that contains information about the employee, including their name, age, job, and address.
  • The name key maps to the string value John Doe, which is the employee’s name. The age key maps to the integer value 35, which is the employee’s age.
  • The job key maps to an object that contains information about the employee’s job. This object includes the employee’s job title, department, and years of experience.
  • The address key maps to an object that contains information about the employee’s address. This object includes the employee’s street, city, state, and zip code.

The corresponding python dictionary for the above YAML file looks as follows.

employee_dict={'employee': {'name': 'John Doe',  'age': 35,
  'job': {'title': 'Software Engineer','department': 'IT','years_of_experience': 10},
  'address': {'street': '123 Main St.', 'city': 'San Francisco','state': 'CA', 'zip': 94102}}}

Let us now discuss how to convert a dictionary to a YAML string or file.

Python Dictionary to a YAML String

To convert a python dictionary into a YAML string, we can use the dump() method defined in the yaml module. The dump() method takes the dictionary as its input argument and returns the YAML string after execution. You can observe this in the following example.

import yaml
employee_dict={'employee': {'name': 'John Doe',  'age': 35,
  'job': {'title': 'Software Engineer','department': 'IT','years_of_experience': 10},
  'address': {'street': '123 Main St.', 'city': 'San Francisco','state': 'CA', 'zip': 94102}}}
print("The python dictionary is:")
print(employee_dict)
yaml_string=yaml.dump(employee_dict)
print("The YAML string is:")
print(yaml_string)

Output:

The python dictionary is:
{'employee': {'name': 'John Doe', 'age': 35, 'job': {'title': 'Software Engineer', 'department': 'IT', 'years_of_experience': 10}, 'address': {'street': '123 Main St.', 'city': 'San Francisco', 'state': 'CA', 'zip': 94102}}}
The YAML string is:
employee:
  address:
    city: San Francisco
    state: CA
    street: 123 Main St.
    zip: 94102
  age: 35
  job:
    department: IT
    title: Software Engineer
    years_of_experience: 10
  name: John Doe

Convert Dictionary to YAML File in Python

We can also use the dump() method to convert a python dictionary to a YAML file. For this, we will use the following steps.

  • First, we will open a YAML file in write mode using the open() function. The open() function takes the file name as its first input argument and the python literal “w” as its second input argument. After execution, it returns a file pointer. 
  • Once we get the file pointer, we will pass it to the dump() method as the second input argument and the dictionary will be the first input argument. After execution, the dump() method will save the contents of the dictionary in YAML format.
  • Finally, we will close the file using the close() method.

You can observe the entire process in the following example.

import yaml
employee_dict={'employee': {'name': 'John Doe',  'age': 35,
  'job': {'title': 'Software Engineer','department': 'IT','years_of_experience': 10},
  'address': {'street': '123 Main St.', 'city': 'San Francisco','state': 'CA', 'zip': 94102}}}
print("The python dictionary is:")
print(employee_dict)
file=open("person_data.yaml","w")
yaml.dump(employee_dict,file)
file.close()
print("YAML file saved.")

Output:

The python dictionary is:
{'employee': {'name': 'John Doe', 'age': 35, 'job': {'title': 'Software Engineer', 'department': 'IT', 'years_of_experience': 10}, 'address': {'street': '123 Main St.', 'city': 'San Francisco', 'state': 'CA', 'zip': 94102}}}
YAML file saved.

The output YAML file looks as follows.

Output YAML File
Output YAML File

Conclusion

In this article, we have discussed how to convert a python dictionary to a YAML string or file. 

To learn more about python programming, you can read this article on how to convert JSON to YAML in Python. You might also like this article on custom json encoders in python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us