How to transform in Swift a dictionary of array values to a dictionary of keys by values

Example:
From: ["Key1":[1,2,3], "Key2", [4,5,6]]
To: ["Key1": 1, "Key1": 2, "Key1": 3, "Key2":4, "Key2": 5, "Key2": 6]

The keys of a Dictionary are unique (there cannot be more than one eg "Key1" key), that's one of the defining features of a dictionary / hash table data structure.

3 Likes

As @Jens said, Dictionary keys are unique. If you want a mapping from keys to multiple values, [Key: [Value]] is the way to achieve that, which is exactly what you already have.

So that begs the question: what's insufficient about [Key: [Value]] that makes you want to transform it in the way you describe?

As the others have said, a dictionary has unique keys, so this cannot really be done. If what you really want a list of pairs, then you might want to try transforming it into an array of tuples. The end result could look something like this:

[("Key1", 1), ("Key1", 2), ("Key1", 3), ("Key2", 4), ("Key2", 5), ("Key2", 6)]

If you need help writing code to do that, just let us know!

1 Like

This wouldn't solve the general problem but, in your specific example, you can use the values as keys in the first place. Is that a reasonable solution for your actual case?

That's exactly what I want, I express badly

I think you can do something like this:

let originalDictionary = [
    "Key1": [1,2,3], 
    "Key2": [4,5,6]
]

// to get [("Key1", 1), ("Key1", 2), ("Key1", 3), ("Key2", 4), ("Key2", 5), ("Key2", 6)]
let arrayOfTuples = originalDictionary.flatMap { element in
	element.value.map {
		(element.key, $0)
	}
}

// to get [["Key1": 1], ["Key1": 2], ["Key1": 3], ["Key2": 4], ["Key2": 5], ["Key2": 6]]
let arrayOfDictionaries = originalDictionary.flatMap { element in
	element.value.map {
		[element.key: $0]
	}
}
2 Likes
Terms of Service

Privacy Policy

Cookie Policy