How would in join a dictionary in Julia similar to like what one of the Python ways is:
diction = {"DC": 4,
"NH": 1,
"MI": 36,
"MO": 4989,
"FL": 157,
"UT": 13,
"NV": 9,
"CA": 110,
"WV": 6,
"NY": 39,
"ME": 1,
"SC": 26,
"KY": 71}
stri = ' | '.join(map(lambda x: '%2.2s %5.5s' % (str(x[0]), str(x[1])), diction.items()))
What I have come up with:
diction = Dict(["DC" => 4
"NH" => 1,
"MI" => 36,
"MO" => 4989,
"FL" => 157,
"UT" => 13,
"NV" => 9,
"CA" => 110,
"WV" => 6,
"NY" => 39,
"ME" => 1,
"SC" => 26,
"KY" => 71])
stri = [@sprintf("%2.2s %5.5s | ",st,ct) for st,ct in keys(diction),values(diction)]
Yields:
ERROR: syntax: invalid iteration specification
OUTPUT:
DC 4 | NH 1 | MI 36 | MO 4989 | FL 157 | UT 13 | NV 9 | CA 110 | WV 6 | NY 39 | ME 1 | SC 26 | KY 71
In recent Julia versions, you need to pull in the sprintf macros with "using Printf". In addition, when you iterate a dictionary, you need to wrap the key-value pair in parentheses (st, ct)
(which Python does not require; this also applies to enumerated for loops). In addition, you should still use a join
here, or the line will end with your '|' separator.
This then becomes:
using Printf
diction = Dict(["DC" => 4,
"NH" => 1,
"MI" => 36,
"MO" => 4989,
"FL" => 157,
"UT" => 13,
"NV" => 9,
"CA" => 110,
"WV" => 6,
"NY" => 39,
"ME" => 1,
"SC" => 26,
"KY" => 71])
stri = join([@sprintf("%2.2s %5.5s", st, string(ct)) for (st,ct) in diction], " | ")
println(stri)