Reputation: 466
My question originated where I had a dictionary of DataFrame values (with compatible columns), and I want to vcat
them all together.
Consider how the string
function can take any number of string arguments:
string("Fish ", "and ", "chips ") == "Fish and chips "
(is true
). I have a dictionary
myLunch = Dict(:a => "Fish ", :b => "and ", :c => "chips ")
and I want to unpack the dictionary and pass its values to string
as though they were arguments.
string( unpack(myLunch)) == "Fish and chips "
Analogously, my data might be stored in an array, lunch = ["Fish ", "and ", "chips "]
, and I want to pass the array's contents as arguments:
string( unpack(lunch) )
How can you do this?
Here is a related post on StackOverflow for tuples
Upvotes: 1
Views: 715
Reputation: 4510
First a little renaming for clarity:
luncharray = ["Fish ", "and ", "chips "]
lunchdict = Dict(:a => "Fish ", :b => "and ", :c => "chips ")
For an array, you just splat it into several arguments, just like you could for a tuple:
string(luncharray...)
Dictionaries are key-value pairs, and you can iterate over its values. You can splat any iterable into several arguments:
# don't care about order
# only need values of Dict
string(values(lunchdict)...)
The problem with the dictionary is that it doesn't preserve an order like arrays do; you can't even count on insertion order. It's possible to get something like and Chips Fish
. Therefore, we have to sort it ourselves. Coincidentally, ["Fish", "and", "Chips"]
is already in order, but we usually don't want to sort by words. Your keys are :a, :b, :c
to indicate order, so lets sort by that.
# care about order
# value from key # sort an array of keys in the Dict
string((lunchdict[key] for key in sort(collect(keys(lunchdict))))...)
Upvotes: 4