Count occurrences of part key value in Dict (Swift) - swift

Lets say I have a dict containing the following values and keys
let dict = ["Foo" : 1,
"FooBar" : 2,
"Bar" : 3,
"BarBar" : 4,
"FooFoo" : 5 ]
My question is :-
How would one count the occurrences of the KEY containing or partly containing the key string "Foo"
The result should be 3 ("Foo","FooBar","FooFoo" )
One direction I am looking at is using
print( dict.keys .contains("Foo"))
This of course returns true
print( dict.keys .contains("Fo"))
It will return a false value when in actual fact "Fo" occurs 3 times but only as a part key name.
Hoping that makes sense :F
So again how do I count the par key name occurrences in a given dictionary

You need to filter the keys and then count them
let arr = dict.keys.filter{ $0.contains("Fo") }
print(arr.count)

A straightforward way is this:
dict.filter{ $0.key.contains("Foo") }.count
We leave all the keys that conatins "Foo" in the dictionary and count the number of KVPs left!

Related

Ordering of Dictionary Swift

I'm trying to work through a problem at the moment which is currently doing the rounds on the internet. The problem is: Given an array of characters, find the first non repeating character. I had a go at it and solved it but I was curious about how other people solved it so I did some looking around and found this answer:
let characters = ["P","Q","R","S","T","P","R","A","T","B","C","P","P","P","P","P","C","P","P","J"]
var counts: [String: Int] = [:]
for character in characters {
counts[character] = (counts[character] ?? 0) + 1
}
let nonRepeatingCharacters = characters.filter({counts[$0] == 1})
let firstNonRepeatingCharacter = nonRepeatingCharacters.first!
print(firstNonRepeatingCharacter) //"Q"
Source: Finding the first non-repeating character in a String using Swift
What I don't understand about this solution, is why it always returns Q, when there are other elements "S" "A" "B" and "J" that could be put first when the filter is applied to the dictionary. My understanding of dictionaries is that they are unordered, and when you make one they change from run to run. So if I make one:
let dictionary:[String:Int] = ["P": 9, "C": 8, "E": 1]
And then print 'dictionary', the ordering will be different. Given this, can anyone explain why the solution above works and maintains the order in which the dictionary elements were added?
You are not looking correctly at the code. The filter is not applied to a dictionary. It is applied to the array (characters), which has a defined order. The dictionary is used only to store counts.

Swift: Get max value for key in array of dictionaries

I have an array containing dictionaries.
let arr = [["test":1], ["test":2], ["test":3], ["test":4]]
I now need to get the one dictionary that contains the highest value for the key "test" (without iterating through everything). I was thinking about filter(_:) but this will only filter out. map(_:) also does not work as I need to filter and not to map.
There's an example how to get the key with the highest value in a dictionary but this does not work in this case.
let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue)
Any help is appreciated!
You can use max much like in your example.
let arr = [["test":1], ["test":4], ["test":3], ["test":2]]
print(arr.max { $0["test"]! < $1["test"]! })
This gives the dictionary with the highest value.
Of course the use of ! is bad unless it is guaranteed that each dictionary really has a "text" key.
Also note that using max will still result in the entire array being iterated. You can't avoid that unless your dictionaries are always sorted by the value. Then in that case simply use last instead of max.

Unclear Swift coding

var occurences: [Int : Int] = [:]
for number in numbers {
if var value = occurences[number] {
occurences[number] = ++value
} else {
occurences[number] = 1
}
}
I understand the first 2 lines that it declares an empty dictionary and I have an array of numbers to iterate in a for-in loop, but can someone explain the 4th and 5th line, please. I just don't get how it declares which one is the key and which one is the value. Thank you so much, stucking here for like 2 days.
This line
if var value = occurences[number]
means that it checks to see if occurences has some value stored for key number and then in next line
occurences[number] = ++value
it increments the value by using ++ and then saves that to the occurences dict.

Adding integers from a dictionary together

Looking to add together integers from a dictionary. For example:
var dictionary = ["one": 1, "two": 2, "three": 3, "four": 4, "five": 5]
I would want to get the sum of 1+2+3+4+5 = 15
I understand it will probably need a loop something like
for (n, i) in dictionary {
*some math function*
}
any help would be appreciated maybe I'm just over thinking this one?
You can use reduce:combine: to get the sum.
With Swift 2.0, reduce:Combine: is added to the protocol extension of SequenceType. So, it is available to all SequenceType like Array, Set or Dictionary.
dictionary.reduce(0) {
sum, item in
return sum + item.1
}
item inside the closure is tuple representing each (key, value) pair. So, item.0 is key where as item.1 is value.The initial value of the sum is 0, and then each time the iteration takes place, sum is added to the value extracted from dictionary.
You could also write it in short as,
dictionary.reduce(0) { return $0 + $1.1 }
While older version of Swift, it has reduce method with Array only. So, we could first get array and apply reduce:combine to get the sum as,
let a = dictionary.values.array.reduce(0) { return $0 + $1 }

Adding Values In Dictionary With Swift

I have this Dictionary:
var dict = ["cola" : 10, "fanta" : 12, "sprite" : 8]
and I want to add the values for example to have the result as 30 , how can I do that? In other words, how can I only add the numbers, not the words?
Since an answer has been accepted and it isn't a very good one, I'm going to have to give up on the socratic method and show a more thematic way of answering this question.
Given your dictionary:
var dict = ["cola" : 10, "fanta" : 12, "sprite" : 8]
You get the sum by creating an array out of the dict.values and reducing them
let sum = Array(dict.values).reduce(0, +)
Or you could use the bare form of reduce which doesn't require the array to be created initially:
let sum = reduce(dict.values, 0, +)
Or the more modern version, since reduce is defined on an Array
let sum = dict.values.reduce(0, +)
The accepted answer doesn't use the power of swift
and the answer that does is outdated.
The simplest updated solution is:
let valuesSum = dict.values.reduce(0, +)
start with zero, and sum the values of all the elements
As explained in the documentations here. You access and modify a dictionary through its methods and properties, or by using subscript syntax. Read the doc.
var dict = ["cola" : 10, "fanta" : 12, "sprite" : 8]
To access a value in your dictionary you can use the subscript syntax:
if let cola = dict["cola"] as? Int { // to read the value
// Do something
}
dict["cola"] = 30 // to change the value
dict["pepsi"] = 25 // to add a new entry to your dictionary
dict["fanta"] = nil // to delete the fanta entry.
to read all the value in your dictionary
var sum = 0
for (drinkName, drinkValue) in dict {
println("\(drinkName): \(drinkValue)")
sum += drinkValue
}
or you can
var sum = 0
for drinkValue in dict.values {
sum += drinkValue
}