Python load yaml to dict

How to Convert YAML to Dictionary in Python

In this article, we are going to see how to convert YAML to Dictionary in Python with the help of examples. Most of the time as a developer your requirement is that convert any YAML file to a Python dictionary, Then in that situation, you have an option to convert any YAML document or any YAML file to a Python dictionary. Python provides an external module pyyaml that is capable of converting YAML to Dictionary.

Prerequisites

Python provides two types of packages first is built-in packages that come with Python by default and the second is external packages that are installed using the pip command. So, to convert YAML to Dictionary in Python we will use pyyaml packages that come under the external package that means you have to install it by using the pip command.

What is YAML

YAML stands for Yet Another Markup Langauge. It is a human-readable data serialization language that is mainly used for writing configuration files where data is being stored or transmitted.
It is becoming very popular in the last few years because it provides an intuitive serialize manner to make build configuration files.
You can see below the document that is an example of YAML.

Читайте также:  Java return что это

YAML Document:

 name: "Vishvajit" age: 23 address: Noida Occupation: Software Developer Skills: - Python - Django - Flask - FastAPI - DRF ( Django Rest Framework )

How to Convert YAML to Dictionary in Python

Here we will convert YAML to Python Dictionary in two ways first it uses a simple YAML string and another is from the YAML file.

Convert YAML to Python Dictionary

In this section, we will see the conversion of the YAML string to a Python dictionary.

Example: Convert YAML to Python Dictionary

 import yaml from pprint import pprint #yaml document yaml_document = """ name: "Vishvajit" age: 23 address: Noida Occupation: Software Developer Skills: - Python - Django - Flask - FastAPI - DRF ( Django Rest Framework ) """ # convert yaml document to dict data = yaml.load(yaml_document, Loader=yaml.Loader) pprint(data)

Convert YAML file to Python Dictionary

In this section, you will see how to convert the YAML file to Dictionary in Python using Python pyyaml package.

Students.yaml

 --- data: - name: "Vishvajit" age: 23 address: Noida Occupation: Software Developer Skills: - Python - Django - Flask - FastAPI - DRF ( Django Rest Framework ) - name: "John" age: 30 address: UK Occupation: front-end Developer Skills: - HTML - JavaScript - React - Angular - Nodejs

Example: Convert YAML file to Python Dictionary

 import yaml from pprint import pprint with open("students.yaml", "r") as file: data = yaml.load(file, Loader=yaml.FullLoader) pprint(data)

Conclusion

So, In this article, we have seen all about how to convert YAML to Dictionary in Python. Most of the time as a developer you have a YAML file and you want to convert it into Python native data type dictionary, Then you can follow the above approach.

I hope this article will help you to convert YAML to Python Dictionary, If you like this article, please share and keep visiting for further Python tutorials.

Related Articles:-

  • How to convert Dictionary to Excel in Python
  • How to convert Excel to Dictionary in Python
  • How to convert string to DateTime in Python
  • How to sort the list of Dictionaries in Python

PyYaml documentation:- Click Here

Источник

How to Read YAML File to Dict in Python

read yaml file to dict in python

YAML stands for YAML Ain’t Markup Language, and is used to define different kinds of configurations and schemas for websites & databases. It is easy to use and understand. Sometimes you may want to convert YAML file to python dict, or write YAML to dict in Python. In this article, we will look at how to read YAML file to dict in Python.

The main benefits of using YAML files are that they portable across programming languages, extensive and support Unicode characters. It is more human-readable than other markup files like XML or even HTML for that matter. It supports a wide range of data types, including maps, lists and scalars.

How to Read YAML File to Dict in Python

Here are the steps to read YAML file to dict. Let us say you have the following YAML file at /home/ubuntu/data.yaml

# An example YAML file instance: Id: i-aaaaaaaa environment: us-east serverId: someServer awsHostname: ip-someip serverName: somewebsite.com ipAddr: 192.168.0.1 roles: [webserver,php]

We will use pyyaml library to parse YAML file. You can install with the following command.

Here is the code to parse this YAML file

import yaml with open("/home/ubuntu/data.yaml", 'r') as stream: try: parsed_yaml=yaml.safe_load(stream) print(parsed_yaml) except yaml.YAMLError as exc: print(exc)

In the above code, we import pyyaml as yaml library. Then we open the data.yaml file using open() function and use yaml.safe_load() function .

You can also use yaml.load() function to load YAML file. It is just that safe_load function will prevent python from executing any arbitrary code in the YAML file.

Once the file is loaded you can display or process its values as per your requirement. The loaded YAML file works like a python object and you can reference its elements using keys. Here is an example.

>>> print(parsed_yaml['instance']['roles']) ['webserver', 'php']

You can even iterate through its items like you do in a dictionary.

>>> for key, value in parsed_yaml.iteritems(): print key, value environment us-east roles ['webserver', 'php'] awsHostname ip-someip serverName somewebsite.com ipAddr 192.168.0.1 serverId someServer Id i-aaaaaaaa

That’s it. In this article, we have looked at how to load YAML file to python dictionary, and also how to access its values.

Источник

Библиотека YAML в Python

В этом руководстве мы узнаем, как использовать библиотеку YAML в Python 3. В последние годы она стала очень популярной благодаря использованию для хранения данных в виде сериализованных файлов конфигурации. Поскольку YAML по сути является форматом данных, библиотека YAML довольно простая, поскольку единственная необходимая функциональность – это возможность анализировать файлы в формате YAML.

В этой статье мы начнем с рассмотрения того, как данные хранятся в файле YAML, а затем загрузим эти данные в объект Python. Наконец, мы узнаем, как сохранить объект Python в файле YAML.

Прежде чем мы двинемся дальше, есть несколько предварительных условий для этого урока. Вы должны иметь базовое представление о синтаксисе Python или иметь хотя бы начальный опыт программирования на каком-либо другом языке.

Установка

Процесс установки YAML довольно прост. Это можно сделать двумя способами, начнем с простого.

Метод 1: через точку

Самый простой способ установить библиотеку YAML в Python – через диспетчер пакетов pip. Если в вашей системе установлен pip, выполните следующую команду, чтобы загрузить и установить YAML:

Метод 2: через источник

Если у вас не установлен pip или у вас возникли проблемы с описанным выше методом, вы можете перейти на исходную страницу библиотеки. Загрузите репозиторий в виде zip-файла, откройте терминал или командную строку и перейдите в каталог, в который загружен файл. Когда вы окажетесь там, выполните следующую команду:

Примеры кода

В этом разделе мы узнаем, как обрабатывать (манипулировать) файлами YAML, начиная с того, как их читать, то есть как загружать их в наш скрипт Python, чтобы мы могли использовать их в соответствии с нашими потребностями.

Чтение файлов

В этом разделе мы увидим, как читать файлы YAML в Python. Начнем с создания двух файлов в формате YAML.

Содержимое первого файла выглядит следующим образом:

# fruits.yaml file apples: 20 mangoes: 2 bananas: 3 grapes: 100 pineapples: 1

Содержимое второго файла выглядит следующим образом:

# categories.yaml file sports: - soccer - football - basketball - cricket - hockey - table tennis countries: - Pakistan - USA - India - China - Germany - France - Spain

Вы можете видеть, что файлы fruit.yaml и category.yaml содержат разные типы данных. Первый содержит информацию только об одном объекте, то есть о фруктах, а второй содержит информацию о видах спорта и странах.

Давайте теперь попробуем прочитать данные из двух файлов, которые мы создали с помощью скрипта Python. Метод load() из модуля yaml можно использовать для чтения файлов YAML. Взгляните на следующий скрипт:

# process_yaml.py file import yaml with open(r'E:\data\fruits.yaml') as file: # The FullLoader parameter handles the conversion from YAML # scalar values to Python the dictionary format fruits_list = yaml.load(file, Loader=yaml.FullLoader) print(fruits_list)

В приведенном выше скрипте мы указали yaml.FullLoader в качестве значения для параметра Loader, который загружает полный язык YAML, избегая выполнения произвольного кода. Вместо использования функции загрузки и последующей передачи yaml.FullLoader в качестве значения параметра Loader вы также можете использовать функцию full_load(), как мы увидим в следующем примере.

Давайте теперь попробуем прочитать второй файл YAML аналогичным образом, используя скрипт Python:

# read_categories.py file import yaml with open(r'E:\data\categories.yaml') as file: documents = yaml.full_load(file) for item, doc in documents.items(): print(item, ":", doc)

Поскольку в файле category.yaml 2 документа, мы выполнили цикл, чтобы прочитать их оба.

sports : ['soccer', 'football', 'basketball', 'cricket', 'hockey', 'table tennis'] countries : ['Pakistan', 'USA', 'India', 'China', 'Germany', 'France', 'Spain']

Как видно из последних двух примеров, библиотека автоматически обрабатывает преобразование данных в формате YAML в словари и списки Python.

Запись

Теперь, когда мы узнали, как преобразовать файл YAML в словарь Python, давайте попробуем сделать что-то наоборот, то есть сериализовать словарь Python и сохранить его в файл в формате YAML. Для этого воспользуемся тем же словарем, который мы получили в результате нашей последней программы.

import yaml dict_file = [, ] with open(r'E:\data\store_file.yaml', 'w') as file: documents = yaml.dump(dict_file, file)

Метод dump() принимает словарь Python как первый, а объект File как второй параметр.

После выполнения приведенного выше кода в вашем текущем рабочем каталоге будет создан файл с именем store_file.yaml.

# store_file.yaml file contents: - sports: - soccer - football - basketball - cricket - hockey - table tennis - countries: - Pakistan - USA - India - China - Germany - France - Spain

Еще одна полезная функция, которую предлагает библиотека YAML для метода dump(), – это параметр sort_keys. Чтобы показать, что он делает, применим его к нашему первому файлу, то есть fruit.yaml:

import yaml with open(r'E:\data\fruits.yaml') as file: doc = yaml.load(file, Loader=yaml.FullLoader) sort_file = yaml.dump(doc, sort_keys=True) print(sort_file)
apples: 20 bananas: 3 grapes: 100 mangoes: 2 pineapples: 1

В выводе видно, что фрукты отсортированы в алфавитном порядке.

Заключение

В этом кратком руководстве мы узнали, как установить библиотеку Python YAML (pyyaml) для управления файлами в формате YAML. Мы рассмотрели загрузку содержимого файла YAML в нашу программу Python в виде словарей, а также сериализацию словарей и сохранение их ключей. Библиотека довольно краткая и предлагает только основные функции.

Источник

Оцените статью