Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

values and keys guaranteed to be in the consistent order?

When applied to a Dict, will values(...) and keys(...) return items in matching order?

In other words, is zip(keys(d), values(d)) guaranteed to contain precisely the key-value pairs of the dictionary d?

like image 398
becko Avatar asked Aug 17 '16 16:08

becko


1 Answers

Option 1

The current Julia source code indicates that the keys and vals of a Dict() object are stored as Array objects, which are ordered. Thus, you could just use values() and keys() separately, as in your question formulation. But, it is dangerous to rely on under the hood implementation details that aren't documented, since they might be changed without notice.

Option 2

An OrderedDict from the DataStructures package (along with the functions values() and keys()) is probably the simplest and safest way to be certain of consistent ordering. It's ok if you don't specifically need the ordering.

Option 3

If you don't want to deal with the added hassle of installing and loading the DataStructures package, you could just use Julia's built in syntax for handling this kind of thing, e.g.

Mydict = Dict("a" => 1, "b" => 2, "c" => 1)

a = [(key, val) for (key, val) in Mydict]

The use of zip() as given in the question formulation just adds complexity and risk in this situation.

If you want the entities separate, you could then use:

Keys = [key for (key, val) in Mydict]
Values = [val for (key, val) in Mydict]

or just refer to a[idx][1] for the idx element of Keys when you need it.

like image 185
Michael Ohlrogge Avatar answered Nov 27 '22 14:11

Michael Ohlrogge