0

i have two arrays like these

var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]

i want to create a new dictionary that have first element of first array and first element of second array and so on. when the third element of first array comes it should again get the first element of second array.

for example:-

dict = ["han" : "hello", "Ji" : "Ji", "Kidda" : hello, "Ho" : "Ji", "Tusi" : "hello"]
2
  • 1
    Dictionary keyed by what? Show exactly the desired output for the given input. Commented Jul 24, 2019 at 15:53
  • i edited the question sir. please have a look. Commented Jul 24, 2019 at 16:18

5 Answers 5

1

If the second array has 2 items you can do

var dict = [String: String]()
for (index, item) in arr1.enumerated() {
    dict[item] = arr2[index % 2]
}
Sign up to request clarification or add additional context in comments.

Comments

1

I believe this is what you're looking for (using arr1 as the keys and arr2 as the values repeating them as necessary):

var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]

let dict = Dictionary(uniqueKeysWithValues: zip(arr1, arr1.indices.map { arr2[$0 % arr2.count] }))

print(dict)
["Kidda": "hello", "Ji": "Ji", "han": "hello", "Ho": "Ji", "Tusi": "hello"]

Note:

Dictionaries have no specified ordering. Only the key/value pairings matter. This matches the example in your question.

Explanation:

zip is used to create a sequence of (key, value) tuples from two sequences that will become the key/value pairs for the new Dictionary. The keys come from arr1. map is used to generate the sequence of values from arr2 repeating them as many times as necessary to match the count of arr1. This sequence of (key, value) tuples is passed to Dictionary(uniqueKeysWithValues:) to turn that sequence into the desired Dictionary.

Comments

0

try:

var dict = ["arr1" : "hello", "arr2" : "Ji"]

then for third you can append by

dict[3] = ["arr3" : String(arr3.first())]

Comments

0

Try this:

var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]

var dict : [String : String] = [:]

var arr2Index = 0

for index in 0..<arr1.count {
    let arr1Value = arr1[index]

    if arr2Index == arr2.count {
        arr2Index = 0
    }

    let arr2Value = arr2[arr2Index]

    dict[arr1Value] = arr2Value

    arr2Index += 1
}

Comments

0

Here's a fun way:

let arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
let arr2 = ["hello", "Ji"]
let arr3 = Array(repeating: arr2, count: arr1.count).joined()
let d = zip(arr1,arr3).reduce(into: [String:String]()) { $0[$1.0] = $1.1 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.