1
$\begingroup$
list =
 {{"aar", "usa", "aer", "NYSE:AIR"}, {"aar", "bel", "sto","F:AIR"}, {"activision", "usa", "sof", "NASDAQ:ATVI"}, {"adidas", "deu", "sto", "F:ADS"}};

AssociationThread[list[[All, 1]] -> Map[Rest, list]]

<|"aar" -> {"bel", "sto", "F:AIR"}, "activision" -> {"usa", "sof", "NASDAQ:ATVI"}, "adidas" -> {"deu", "sto", "F:ADS"}|>

Almost perfect, but two questions remain:

How would you write this?

Why do I lose the first entry of my list?

$\endgroup$
8
  • $\begingroup$ What is an expected result? $\endgroup$
    – Kuba
    Apr 9, 2015 at 18:57
  • 1
    $\begingroup$ Right. "Almost perfect" means nothing to us unless you tell us what is perfect. $\endgroup$ Apr 9, 2015 at 18:57
  • $\begingroup$ Perfect means that the missing first entry should be "aar" -> {"usa", "aer", "NYSE:AIR"} $\endgroup$
    – eldo
    Apr 9, 2015 at 19:13
  • 1
    $\begingroup$ from AssociationThread>>Details: If any of the keys are repeated, later instances replace earlier ones $\endgroup$
    – kglr
    Apr 9, 2015 at 19:17
  • $\begingroup$ @kguler So I can't work with duplicate / multiple keys ? $\endgroup$
    – eldo
    Apr 9, 2015 at 19:21

2 Answers 2

8
$\begingroup$

From the docs AssociationThread>>Details:

If any of the keys are repeated, later instances replace earlier ones.

And Association >> Details:

If there are multiple elements with the same key, all but the last of these elements are dropped. Merge yields instead a list of values for repeated keys.

Merge[Thread[list[[All, 1]] -> Map[Rest, list]], Identity]
(* <|aar->{{usa,aer,NYSE:AIR},{bel,sto,F:AIR}},
     activision->{{usa,sof,NASDAQ:ATVI}},
     adidas->{{deu,sto,F:ADS}}|> *)
$\endgroup$
0
0
$\begingroup$

If you know you are going to get duplicate keys you should consider having a full set of keys for your association.

list = {{"aar", "usa", "aer", "NYSE:AIR"}, {"aar", "bel", "sto", 
"F:AIR"}, {"activision", "usa", "sof", "NASDAQ:ATVI"}, {"adidas", 
"deu", "sto", "F:ADS"}};

header = {"company", "country", "stock type", "ticker"};

AssociationThread[header -> #] & /@ list

Then if you can pull keys and values far more flexibly - also consider turning it into a Dataset for more flexible querying.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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