# Tag Info

26

Summary Important differences between Association and CreateDataStructure["HashTable"] include: associations are immutable whereas hash tables are mutable associations are hash array mapped tries as opposed to simple hash tables Mutability As a rule, Wolfram Language's native data structures are immutable. Any attempt to change even just a part ...

19

Preamble The real problem here seems somewhat deeper than what the (mostly correct) observations in comments indicate. In Mathematica, a number of objects, which are so-called raw objects (including in particular Association, SparseArray, and Rational) require a non-trivial construction stage, which usually happens during evaluation. Had Mathematica's ...

8

There is a Lookup variant that supports wrapping with a head before evaluation: Lookup[assoc, key, Missing[], Hold]

7

dayNameToISOWeekDay = DateValue[DayRound[{2021, 1}, #], "ISOWeekDay"] &; KeySortBy[dayNameToISOWeekDay] @ assoc <|Monday -> 107900, Tuesday -> 116500, Wednesday -> 122150, Thursday -> 119450, Friday -> 124350, Saturday -> 92000, Sunday -> 85800|> Update: To have the week start from Sunday: isoWeekDay = ...

7

Ironically, the probably simplest answer is literally Extract, just as in the question's title: Extract[assoc, {Key[key]}, Hold] (* Hold[value] *)

7

The issue is indeed that since both defaulter and Length are ascending operators, they are applied "bottom-up". That is, Length is applied to the lowest level prior to defaulter being applied to the middle level. We can defer the operation of Length so that it is processed after defaulter by means of a subquery: dta // Query[All, defaulter /* ...

6

If you are willing to use input aliases to enter the dot, you could do: CurrentValue[EvaluationNotebook[],{InputAliases,"."}] = TemplateBox[ {}, "Accessor", DisplayFunction->("."&), InterpretationFunction:>("@"&), SyntaxForm->"@" ]; Note that this overrides the standard ...

6

You could define a function, to be used by "SortBy", that determines the ordering. E.g.: assoc = <|Wednesday -> 122150, Thursday -> 119450, Friday -> 124350, Saturday -> 92000, Sunday -> 85800, Monday -> 107900, Tuesday -> 116500|> by[day_] = Switch[day, Sunday, 1, Monday, 2, Tuesday, 3, Wednesday, 4, ...

6

Does it fit your needs? Tuple; Begin["ExternalEvaluatePythonPrivate"]; encodeExprToPython[Tuple[]] = "()"; encodeExprToPython[Tuple[a_, b_ : ""]] := StringRiffle[{a, b}, {"(", ",", ")"}] End[] ExportString[<|Tuple[0.52, 1.4] -> 5.1423545`|>, "PythonExpression"] {(0.52,1.4): ...

6

but it would require some adaption and learning a new syntax I recommend adapting and learning new syntax. Associations are atomic objects and normal structural replacement rules should not work on them. This fails In[50]:= Association[{"a" -> 1, "b" -> 2}] /. ("a" -> num_) :> "a" -> 6 Out[50]= <|&...

5

Normally, as @Hausdorff mentioned, you won't get -0.2*{0, 1, 0, 0} + 0.4*{2, 0, 0, 0} + 0.11*{0, 0, 2, 0} + 0.7*{0, 0, 1, 0} as output due to immediate evaluation. But if this is only a simplified example of yours and you're somehow able to preserve the elements in the output, try something like this: assoc = Association[1 -> a, 2 -> b, 3 -> c, 4 -&...

5

Join by year For each year in the list2 item, we get the detailed date by find items with similar year in list1: list1 = {{"City A", DateObject[{2019, 1, 1}]}, {"City B", DateObject[{2020, 1, 1}]}, {"City C", DateObject[{2019, 1, 2}]}}; list2 = {{1, "Cloudy", DateObject[{2019}]}, {1, "Sunny", ...

5

This common data format, where the first row of data has column names, and the following rows are values, is easy to convert to a dataset with AssociationThread. list = {{"date", "time", "volume"}, {a1, a2, a3}, {b1, b2, b3}, {c1, c2, c3}}; ds = Dataset[AssociationThread[First@list, #] & /@ Rest@list] Often, data from ...

5

HashTable seems a bit slower in creating, probably due to compiling, than Association: n = 10^6; ht["Insert", # -> 2 #] & /@ Range[n]; // Timing (*{1.5625, Null}*) as = Association[ Table[i -> 2 i, {i, n}] ]; // Timing (*{0.96875, Null}*) For retrieving there is no big difference, HashTable is slightly faster: n = 10^6; ht["Lookup&...

5

Why is the result Missing["KeyAbsent", 2] + Derivative[1][z[2]][y] Heads are evaluated first. The head of Derivative[0, 0, 1][func][x, 2, y] is Derivative[0, 0, 1][func], which yields the following: Derivative[0, 0, 1][func] (* Missing["KeyAbsent", #2] + Derivative[1][z[#2]][#3] & *) This shouldn't be completely surprising ...

4

This has to do with how Mathematica treats numbers and numerical equality, which can be somewhat involved. Each number has a certain precision: exact, finite, or machine precision. (Machine precision is whatever your computer's hardware uses to do floating-point arithmetic, whereas arbitrary-precision numbers are kept track of explicitly.) Mathematica ...

4

test = <|"key1" -> <|"key11" -> 11, "key12" -> 12, "key13" -> 13|>, "key2" -> <|0 -> <|"X" -> 5, "Y" -> 0|>, 1 -> <|"X" -> 6, "Y" -> 0|>, 2 -> <|"X" -> 7, "Y" -> 0|>, 3 ...

4

Here is one way: ds[Query@GroupBy[First -> Last], Splice@Thread[#team -> #] &] Unlike the expression given in the question, this does not produce nested datasets. But if nested datasets are desired, then: ds[Query[GroupBy[First->Last], Dataset], Splice@Thread[#team -> #] &]

4

Lists in Wolfram Language are simple linear arrays in memory. Such arrays, especially packed numeric arrays, are amenable to numerous optimizations all the way from the C compiler through to the hardware: on-chip CPU caching, speculative evaluation, pipelining, etc. Associations in Wolfram Language are implemented using hash array mapped tries. This is a ...

3

If we can rely upon the target associations always being under "key2" and always having a subkey "X", then: test // MapAt[Select[#X > 6 &], "key2"] % === test2 (* True *) or test // Query[{"key2" -> Select[#X > 6 &]}] In a more general case where we do not know the parent key or even if the ...

3

Disclaimer: elegancy is subjective and efficiency was not tested. Merge[Total] @* KeyValueMap[mealType[#] -> #2 &] /@ <|caloriesOfFoodEaten|>

3

This is not a bug. Compare the output of these two lines: lst /. f[x_, y_] -> dict[x] and lst /. f[x_, y_] :> dict[x] In the first case, dict[x] evaluates to Missing["KeyAbsent", x] and then a value is substituted for x. In the second case, first a value such as Subscript[r,1] is substituted for x in dict[x], obtaining dict[ Subscript[r,1] ]...

3

Ok it is a bit cheeky to answer one's own question but I stubbled on the solution months after wondering what was going wrong. The solution is to convert the output-cell into standard form (command shift N) rather than traditional form (my default). I hope this can prove useful to others.

3

An alternative to using SortBy[..., f] is to create a dedicated ordering function, which then can be used in any sorting operation. For example, let us write a WeekOrder function, from Monday to Sunday: weekdays = {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}; Do[WeekOrder[weekdays[[i]], weekdays[[j]]] = Order[i, j], {i, 7}, {j, 7}] Then ...

3

Since the output of LearnDistribution is a LearnedDistribution object, and since its contents is an association, I'd recommend interrogating the association directly via its keys. To extract the kernel size, then, you could use: First[ld]["Model", "KernelSize"] (* Out: 0.510338 *) In the above, First[ld] returns the association that ...

3

keys = {"Jan 2021", "Feb 2021", "Mar 2021", "Apr 2021", "May 2021", "Jun 2021", "Jul 2021", "Aug 2021", "Sep 2021", "Oct 2021"}; AssociationThread[keys, Defer @ {Missing["NotAvailable"], Missing["NotAvailable"]}](*or*) ...

3

I suppose AssociationThread[Values@assoc, Keys@assoc], but it's not invertible if the values are not distinct. Also Association@KeyValueMap[#2 -> #1 &, assoc] with the same caveat.

2

Basically the following should do (replacing N by n and C by c): SparseArray[ Rule[ Transpose[{ Join @@ KeyValueMap[ConstantArray[#1, Length[#2]] &, n], Join @@ Values[n] }], Join @@ Values[c] ] ] To problem is that your numbers are too large. The matrix has as many rows as the largest key in the association n. And a sparse array has ...

2

If the dataset is a simple "list of associations", and if the column exists as a separate variable, this method is nice and clean: ds = Dataset@{ <| "name" -> "alice", "age" -> "32" |>, <| "name" -> "bob", "age" -> "25" |> } c = {&...

2

The canonical sort of the values returned by DayName is alphabetic, so the Greater parameter sorts as Friday-to-Wednesday in alphabetical order. We can use an association to map the day names to the Sunday-to-Saturday sort order. The association avoids the need to use a function with sort functions. Here are two ways to create the association. daynameOrder = ...

Only top voted, non community-wiki answers of a minimum length are eligible