3
$\begingroup$

I have the following association list. I want to get the first value of the duplicate item, but only the last value. What should I do?

    Merge[{<|a -> 1, b -> 2, b -> 3, a -> 2, c -> 4, d -> 5, 
       c -> 2|>}, Last]
    Merge[{<|a -> 1, b -> 2, b -> 3, a -> 2, c -> 4, d -> 5, 
       c -> 2|>}, First](*The result I want is <|a -> 1, b -> 2, c -> 4, d -> 5|>*)

As Rohit Namjoshi said, can I first convert the relationship list to the normal list {a -> 1, b -> 2, b -> 3, a -> 2, c -> 4, d -> 5, c -> 2} and then try to achieve the goal?

$\endgroup$
  • 2
    $\begingroup$ An Association cannot have duplicate keys.<|a -> 1, b -> 2, b -> 3, a -> 2, c -> 4, d -> 5, c -> 2|> evaluates to <|a -> 2, b -> 3, c -> 2, d -> 5|>. $\endgroup$ – Rohit Namjoshi Feb 25 at 4:28
  • 2
    $\begingroup$ association data struct is like a dictionary in other languages. There is no "first" or "second" or "last", etc.. in association. i.e. there is no order implied. So what you say find the "last" item, then the question itself is not well posed. You can convert association to normal list using the command Normal. $\endgroup$ – Nasser Feb 25 at 5:06
  • 1
    $\begingroup$ @Nasser: Well, there is an ordering of the keys in an association (see KeySort) and you can do asso[[2]] for getting the value of the second key. But doing this is typically asking for trouble... =) $\endgroup$ – Henrik Schumacher Feb 25 at 7:43
  • $\begingroup$ @HenrikSchumacher I was thinking of the values itself. From this "Items in a dictionary are accessed by key and are unordered." And then read that reference.wolfram.com/language/guide/Associations.html says "Associations provide generalizations of .... dictionaries," So that is what I meant. I was thinking of the data itself (values) not keys. That is what I understood by question above when it said "duplicate item". $\endgroup$ – Nasser Feb 25 at 8:04
  • $\begingroup$ @Nasser I meant my comment more as an addition to your comment, not as criticism. $\endgroup$ – Henrik Schumacher Feb 25 at 8:42
5
$\begingroup$

In version 10.1 and using a plain List of Rules in the input:

Merge[{a -> 1, b -> 2, b -> 3, a -> 2, c -> 4, d -> 5, c -> 2}, First]
Merge[{a -> 1, b -> 2, b -> 3, a -> 2, c -> 4, d -> 5, c -> 2}, Last]
<|a -> 1, b -> 2, c -> 4, d -> 5|>
<|a -> 2, b -> 3, c -> 2, d -> 5|>
|improve this answer|||||
$\endgroup$

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.