Alex Catchpole
Alex Catchpole

Reputation: 137

How can I sort an array into a dictionary?

Let's say I have an array which contain multiple country names such as "Australia, Denmark, United Kingdom, Austria, Australia, Denmark" some of the country names appear twice.

How can I sort them to form a dictionary based on country names. So they key would be the country name and the element would be the country.

If I have two countries in my array that are the same, the key would be the country and the elements would be those two countries.

I need it so that if I add another country it will make a key for the country without having to specify keys beforehand.

Each country needs to be under a key of it's country, not dependent on the occurrences of the country in the array.

I think I've worked out a basic algorithm for it but I can't seem to put it into practice.

  1. While enumerating over the array
  2. check to see if a key in the dictionary matches the current string
  3. If it does, add the string to the dictionary under the matching key
  4. If it doesn't create a key and place the string under the key.

Is this algorithm correct or at least a step in the right direction?

Thanks for the help.

EDIT: We have an array which contains the country names "Australia, Denmark, United Kingdom, Austria, Australia, Denmark"

I need to organise this into a dictionary based on countries so as we have two of the country Denmark in the array I need to sort it so it looks like this:

Denmark: "Denmark", "Denmark"

The key is the country name and the element is the string.

United Kingdom only occurs once so that part of the dictionary will look like this:

United Kingdom: "United Kingdom"

I hope I've made more sense.

Upvotes: 0

Views: 107

Answers (2)

Eendje
Eendje

Reputation: 8883

Not sure if this is what you meant. It's not very clear.

var dict = [String: [String]]()
let countries = ["Holland", "England", "France", "Belgium", "England"]

for country in countries {
    dict[country] = (dict[country] ?? []) + [country]
}

for (key, value) in dict {
    println("KEY: \(key) & VALUE: \(value)")
}

Output:

KEY: England & VALUE: [England, England]
KEY: Belgium & VALUE: [Belgium]
KEY: Holland & VALUE: [Holland]
KEY: France & VALUE: [France]

EDIT:
Simplified based on Martin R's link in his comment.

Upvotes: 4

chedabob
chedabob

Reputation: 5881

The simplest way is to just loop over the array and check if the key exists in the dictionary. Make each value of the dictionary an NSMutableArray.

Upvotes: 0

Related Questions