0

How to Join the list based on YAML file, i have below file which need to join by space delimitation.

$ cat File.yml
---
fruits:
 - orange
 - banana
 - apple
 - strawberry
 - berry
 - cherry
... 

What i tried:

>>> import yaml
>>> with open('File.yml') as f:
...   result = yaml.safe_load(f)
...   print(result)
...
{'fruits': ['orange', 'banana', 'apple', 'strawberry', 'berry', 'cherry']}

Can we do something {{ fruits[ item ] | join(' ') }}" ?

Desired:

"orange banana apple strawberry berry cherry"

I don't require "," in the result.

user2023
  • 452
  • 5
  • 22

2 Answers2

1

Just try this:

import yaml


with open('File.yml') as f:
    result = yaml.safe_load(f)
    print(' '.join(result['fruits']))

Output:

orange banana apple strawberry berry cherry
baduker
  • 19,152
  • 9
  • 33
  • 56
1

Just going on top of what you already have.

>>> with open("File.yml") as f:
...   result = yaml.safe_load(f)
>>> " ".join(result["fruits"])
"orange banana apple strawberry berry cherry"

You can refer to the Python docs for a more in-depth description on the syntax of the .join. The gist of it is that we need

str.join(iterable)

In this case, we want to join by empty spaces, " ", and we want to iterate through the contents of result["fruits"]" to join the items into one string.

Jake Tae
  • 1,681
  • 1
  • 8
  • 11