2
$\begingroup$

I have two associations:

assoc1= <|"HD 164019" -> {"1.05", "1.37", "A"}, "* 63 Oph" -> {"-0.77", "0.40", "A"}, "HD 168941" -> {"-3.76", "1.38", "A"}, "* 9 Sgr" -> {"0.49", "0.40", "A"}, "HD 165052" -> {"0.15", "0.63", "A"}, "* zet Oph" -> {"8.91", "0.20", "A"}, "HD 165921" -> {"2.18", "0.67", "A"}, "HD 163800" -> {"-1.01", "0.66", "A"}, "HD 163892" -> {"-0.50", "0.69", "A"}, "HD 313846" -> {"-0.46", "1.79", "A"},.....

assoc2 = <|" HD 164019 " -> {"O9.5IV"}, " * 63 Oph " -> {"O8II"}, " HD 168941 " -> {"O9.5IV"}, " HD 164536 " -> {"O7.5V"}, " NAME Her 36 " -> {"O7:V"}, " * 9 Sgr " -> {"O4V((f))z"}, " HD 164816 " -> {"O9.5V+B0V"}, " HD 165052 " -> {"O7Vz+O7.5Vz"}, " * zet Oph " -> {"O9.2IV"}, " HD 165246 " -> {"O8V"}, " HD 165921 " -> {"O7V+O9V"}, " HD 164492A " -> {"O7.5Vz"}, " HD 163800 " -> {"O7.5III(f)"}, " HD 163892 " -> {"B0.5/B1Ib"}, " HD 313846 " -> {"WN9h"},...

I want to merge them into a single association like this:

assoc3 = " HD 164019 " -> {"O9.5IV","1.05", "1.37", "A"}, " * 63 Oph " -> {"O8II","-0.77", "0.40", "A"}...

I tried

assoc3 = Merge[Join{assoc1, assoc2}, Identity]

but it didn't work.

Has anybody any suggestion on how implement it?

$\endgroup$
  • 3
    $\begingroup$ You can use Merge[{assoc1, assoc2}, Apply@Join] but keep in mind that "HD 164019" is not the same thing as " HD 164019 ". $\endgroup$ – Kuba Aug 29 '15 at 11:45
7
$\begingroup$

The keys in the two associations must be the same. This is not the case in your example. Restricting things to just the first two elements in your associations (enough to make the point), you have

assoc1 = 
   <|"HD 164019" -> {"1.05", "1.37", "A"}, "* 63 Oph" -> {"-0.77", "0.40", "A"}|>;
assoc2 = <|" HD 164019 " -> {"O9.5IV"}, " * 63 Oph " -> {"O8II"}|>;

The extra spaces in the keys of assoc2 are bad and must be removed.

assoc2 = <|"HD 164019" -> {"O9.5IV"}, "* 63 Oph" -> {"O8II"}|>;

Now your problem can be solved with

Merge[{assoc2, assoc1}, Flatten]
<|"HD 164019" -> {"O9.5IV", "1.05", "1.37", "A"}, 
  "* 63 Oph" -> {"O8II", "-0.77", "0.40", "A"}|>

Note that to get the ordering you show in your example, you must give Merge,{assoc2, assoc1}; the order matters.

$\endgroup$
  • 2
    $\begingroup$ just for completeness: KeyMap[StringTrim,assoc2] would remove the extra spaces programmatically... $\endgroup$ – Albert Retey Jan 11 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.