I suspect you have to think through your desired data
structure more before you can write the code you want.
However as a general idea I would suggest having the
initial insertion code always assume the general case
(multiple keys) and then perform a second pass to simplify
the surprised excess. For an example of how to perform
the second pass you can study how XML::Simple
does it.