-1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

3 Answers3

1

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.

Uncommon
  • 3,323
  • 2
  • 18
  • 36
1

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.

zneak
  • 134,922
  • 42
  • 253
  • 328
1

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.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148