Sort Dictionary by Key Based on Values in Array - arrays

How can a dictionary be sorted, by its keys, in the order listed in an array? See example:
Dictionary to sort:
var item = [
"itemName":"radio",
"description":"battery operated",
"qtyInStock":"12",
"countOfChildren":"5",
"isSerialized":"0"
]
Order in which the keys should be sorted:
let sortOrder = [
"itemName",
"qtyInStock",
"countOfChildred",
"description",
"isSerialized"
]
I have tried the following in Playground:
var sortedItem = Dictionary<String, String>()
for i in sortOrder {
sortedItem[i] = item[i]
}
While viewing the value history in Playground displays everything in the correct order, the resulting dictionary is in a seemingly random order.

As mentioned by Tiago, a Dictionary by definition doesn't have an order. It is essentially a mapping of keys to values. I would recommend one of two approaches.
If the ordering you wish to achieve is manual as your question makes it seem. I would create an array to hold ordered keys. Then, at any point you need to, you can cycle through the array (which is order) and print out all of the values found in the dictionary. They will inherently be printed out using the ordered array of keys.
If the ordering is something than be done programmatically, you could grab a reference to all of the keys by doing myDictionary.keys.array. You could then sort the array, then once again, iterate through the array and grab the values from the dictionary.
Example:
let myKeys = myDictionary.keys.array
// sort the keys
for key in myKeys {
println(myDictionary[key])
}
Hope that helps.

A dictionary, by definition, doesn't have an order.
However, you can have an array of sorted items by touples or implement your sorted dictionary.

Related

Swift Array/Dictionary is not printing back in expected order

Im attempting to to combine two swift arrays into a simple swift dictionary. I am extremely new to swift (but know a decent amount of python), and have come across something that I think is rather odd. When I run the code below, I get a dictionary just as expected, however, if I rerun the code, the key:value pairs come up in a different order. I know that dictionaries in swift are supposed to be unordered, but does this mean each time I go to iterate through the key:value pairs of a dictionary, the order of these pairings may change? In other words, is it impossible to preserve the order to the two initial arrays that comprise the dictionary in the final dictionary product?
let cities: Array<String> = ["Paris", "Mexico City", "Rome"]
let countries: Array<String> = ["France", "Mexico", "Italy"]
var newCountrydict : Dictionary<String, String> = [:]
for (city,country) in zip(cities,countries){
newCountrydict[country] = city
}
newCountrydict
In the swift docs, under "Dictionaries":
Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary when you need to look up values based on their identifier, in much the same way that a real-world dictionary is used to look up the definition for a particular word.
It is not possible to preserve the order if you use dictionaries in swift.
In the same docs, it says:
Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.
I suggest you read through the official documents.

Delete and re-index dictionary in Swift

Hi I have a dictionary of type:
1:[[12.342,34.234],[....,...],....]
2:[[......],[....]]....
Now I'd like to know if there are functions to delete specifics key and correspondents value, and a function to re-index it for examples if I delete the value correspondents to key 2 the key 3 should become the key 2 and so on.
I think you need to use an Array, not a Dictionary
var elms: [[[Double]]] = [
[[0.1],[0.2, 0.3]],
[[0.4], [0.5]],
[[0.6]],
]
elms.remove(at: 1) // remove the second element
print(elms)
[
[[0.10000000000000001], [0.20000000000000001, 0.29999999999999999]],
[[0.59999999999999998]]
]
Yes output values are slightly different from the original ones.
To delete a key and value, just do dict[key] = nil.
As for re-indexing, dictionary keys are not in any particular order, and shifting all the values over to different keys isn't how a dictionary is designed to work. If this is important for you, maybe you should use something like a pair of arrays instead.
Dictionaries are not ordered. This means that "key 3" becoming "key 2" is not a supported scenario. If keys have been in the same order that you've inserted them, you've been lucky so far, as this is absolutely not guaranteed.
If you want ordering and your list of key/value pairs is small (a hundred or so is small), you should consider using an array tuples: [(Key, Value)]. This has guaranteed ordering. If you need something bigger than that or faster key lookup, you should find a way to define an ordering relationship between keys (such that you can say that one should always be after some other key), and use a sorted collection like this one.

How do I navigate through each item of a 2D array?

So, I know you can navigate through a 2D array with something like
arr1.each do |a1|
a1.each do |a2|
puts a2
however what I am trying to do is a little different. I have 2 sets of values stored in arrays and I want to be able to cycle through them and populate a dropdown menu from the information.
So I have data like:
names = ["bob", "frank", "tim"]
id = [1, 2, 3]
which gets returned in an array from a method like this:
def method_name
#stuff
return names, id
end
What I want to be able to do in the view is pair the corresponding indexes with each other. So, for the above example, bob-1 frank-2 tim-3 I can't seem to figure it out. I have tried slicing and nested loops and have also tried with a hash being returned instead of an array. I'm lost.
If anyone has any information on how to pull the information the way I am trying to do it, or another simpler way to do it I would really appreciate the input.
names.zip(id).map { |e| e.join('-') }
zip combines the two arrays into an array of arrays like this:
[['bob', 1], ['frank', 2], ['tim', 3]]
map loops through each of 3 elements of the outer array and converts each inner array into a string by joining its two elements together with a dash using join.
See zip, map, and join documentation.
Generally speaking, when researching array manipulation in Ruby, you'll want to look at the docs both for Array and the docs for Enumerable.
This is a rare case in Ruby where iterating on the index is helpful:
(0...names.size).map do |idx|
"#{names[idx]}-#{id[idx]}"
end

MongoDB: Determine index of item in array

Is there a way to determine the index of a retrieved item in an array in MongoDB?
I have an array of object ids inside some document.
{
ids: [id1, id2, id3, ...]
}
I search the array for id3, and if it's found, I also want the position of the object added to the result. In this case, it's so I can insert more objects immediately after it in the array.
If I can't do this, how would I go about creating an ordered list of objects for which I can retrieve and easily modify the position of elements in the ordered list (since an insert operation on the list will result in modifying the position of all elements after the insert)?
answer:
Obtaining the positional index is NOT supported in mongodb. I will open a new question then about redesigning my application to deal with this limitation. Thanks everyone!
The way I see it, you have two choices:
Retrieve the whole array, mutate it however you wish in your language of choice, and update the array in the db with your new array.
Come up with a data structure that supports whatever it is you are ultimately trying to do.

How to perform string operations on the Key of Associative array in TCL

I have an associative array or Hash, is there a way where I can do manipulation on the Key of the Hash.
Forexample: Lets say I have a set of keys in the Keyset of Hash, I want to do some operations(Some string manipulation) on these keys.
Any suggestions on how to do this?
Use array names myarray to retrieve a list of all the keys, then you can do any string manipulation as you want on them
I'm not quite sure from your question whether you're talking about an array or a dictionary value; both are associative maps, but arrays are collections of variables and dictionaries are first-order values.
You can get the keys of an array with the array names command, and of a dictionary with dict keys:
# Note, access with*out* $varname
set keys [array names theArray]
# Note, access *with* $varname
set keys [dict keys $theDict]
In both cases, the keys variable will afterwards hold a normal Tcl list of strings that you can manipulate in any way you want. However, those changes do not reflect back to where they came from (as that isn't how Tcl's value semantics works, and would be really confusing in real code). To change the key of an entry in an array or dictionary, you have to remove the old one and insert the new one; this will (probably) change the iteration order.
set newKey [someProcessing $oldKey]
if {$newKey ne $oldKey} { # An important check...
set theArray($newKey) $theArray($oldKey)
unset theArray($oldKey)
}
set newKey [someProcessing $oldKey]
if {$newKey ne $oldKey} {
dict set theDict $newKey [dict get $theDict $oldKey]
dict unset theDict $oldKey
}
From Tcl 8.6.0 onwards you can also use dict map to do this sort of change with dictionaries:
set theDict [dict map {key value} $theDict {
if {[wantToChange $key]} {
set key [someProcessing $key]
}
# Tricky point: the last command in the sub-script needs to produce the
# value of the key-value mapping. We're not changing it so we use an empty
# mapping. This is one of the many ways to do that:
set value
}]
If you are changing a few keys in a large dictionary, it is more efficient to use dict set/dict unset as described earlier: dict map is optimized for the case where a lot of changes are being made.

Resources