Set-like alternative for yaml files

530 views Asked by At

I'm using a YAML file to store some data to be used by my Python script.

The structure is more or less as follows:

<id1>:
    email: <email address for id 1>
    phone: <phone number for id 1>

<id2>:
    email: <email address for id 2>
    phone: <phone number for id 2>

When parsing this YAML file, I get a dictionary:

{<id1>: {'email': <email address for id 1>, 'phone': <phone number for id 1>}, {<id2>: {'email': <email address for id 2>, 'phone': <phone number for id 2>}}

When using this configuration, the ID is used as the highest level identifier, so to speak. But for my script, this shouldn't be the case: I want to be able to keep the respective data together without putting one of the keys at a higher level. To illustrate, I'd prefer something like this:

id:    <id 1>
email: <email address for id 1>
phone: <phone number for id 1>

id:    <id 2>
email: <email address for id 2>
phone: <phone number for id 2>

When parsing, I should get something like this:

{{'id': <id1>, 'email': <email address for id 1>, 'phone': <phone number for id 1>}, {'id': <id2>, 'email': <email address for id 2>, 'phone': <phone number for id 2>}}

Does such a configuration exist?

1

There are 1 answers

0
Alex Taylor On BEST ANSWER

Are you after an array?

- id:    <id1>
  email: <email address for id 1>
  phone: <phone number for id 1>
- id:    <id2>
  email: <email address for id 2>
  phone: <phone number for id 2>

That will give you something like this:

[{"id": "<id1>", "email": "<email address for id 1>", "phone": "<phone number for id 1>"}, {"id": "<id2>", "email": "<email address for id 2>", "phone": "<phone number for id 2>"}]

If you actually need a dictionary (where id is the key and points to a record that also contains the id), consider using the array format still but then run a line like:

contacts = dict((item["id"], item) for item in original_array)