Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialVera Hsu
997 PointsHow to find the key based on the value in a dictionary?
We already know how to find value from key. Can we reverse it, and find the key based on value?
1 Answer
Steven Deutsch
21,046 PointsHey Vera Hsu,
You have to keep in mind, while keys must be unique - their values can be the same. This means that one value can return multiple keys. There's no simple method that I know of, other than using some higher order function to do the work. However, consider the code below:
// Here we have a dictionary of [String: Int]
let aDict = ["milk": 1, "eggs": 12, "apple": 1, "bacon": 3]
/* We can decompose the dictionary as a tuple of its keys and values with a for loop
We can then use a conditional statement to return the key based on the value */
for (key, value) in aDict {
if value == 1 {
print(key)
}
}
// We can also check if a key exists by checking if it is equal to nil
let keyExists = aDict["milk"] != nil
print(keyExists) // will print true
Hope this helps. Good Luck!