I have a datastructure which is similar to an association:

enter image description here

However, it has duplicate "keys" (different entries with the same date) with different values (measured in hours). What I'd like do is sum the hours ("values") for each of the same key (date) to compress the list. Is this possible?


1 Answer 1


You can use Merge to do this,

    list = {{a, 1}, {a, 2}, {b, 3}, {a, 7}, {c, 14}, {a, 3}, {c, 5}};
    merged = Merge[Rule @@@ list, Total]
    (* <|a -> 13, b -> 3, c -> 19|> *)

You can convert this back to a list of lists easily enough. But if you leave it in this state then you can easily add more data:

    merged = Merge[{merged, <|b -> 4|>}, Total]
    (* <|a -> 13, b -> 7, c -> 19|> *)

Running merged[b] += 4 would have the same effect.


Your Answer

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

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