Re: help with yaml.dump
Kirill Simonov <[email protected]>
| Newsgroups | gmane.text.yaml.general |
|---|---|
| Message-ID | <[email protected]> |
Hi,
> I'm using yaml with Python and I need to create a yaml file with
> alphabet letters and a corresponding coding.
>
> I'd like to have an output like this:
>
> a: 00000
> b: 00001
> ...
>
> and so on.
>
> I wrote this:
>
> for i in alfabeto:
> yaml.dump({i : gmpy.digits(interi,2).zfill(5)}, stream)
>
> but what I get is:
>
> {a: '10110'}
> {b: '10110'}
> {c: '10110'}
> ...
>
> Why does it print the parenthesis { } and apexes ' ' ?
Both
a: '10110'
and
{a: '10110'}
are valid YAML representations of the dictionary, and PyYAML is free to
choose any of them. However you have a limited control over the output
style. You could write
>>> print yaml.dump({'a': '10100'}, default_flow_style=False)
a: '10100'
Note that you'll still get quotes around 10110. That's because the
object '10110' is a string, but looks like a number. If you load the
document
a: 10110
using PyYAML, you'll get the dictionary
{'a': 10110}
which is not equal to the original dictionary {'a': '10110'}. Quotes
around the value indicate that the scalar is a string and allows PyYAML
to produce the same value it has serialized.
Regarding your original problem: perhaps you could simple write
for i in alfabeto:
print "%s: %s" % (i, gmpy.digits(interi,2).zfill(5))
If you want to use PyYAML for this task, you'd better dump the whole
dictionary:
print yaml.dump(dict([(i, gmpy.digits(interi,2).zfill(5))
for i in alfabeto]), stream)
Thanks,
Kirill
-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2005.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/