I'm practicing swift and I'm trying to iterate over a Dictionary to print the key, but it gives me a
fatal error: Dictionary literal contains duplicate keys
How can remove the error?
let people = ["age":14, "age":15, "age":75, "age":43, "age":103, "age":87, "age":12]
for (key, value) in people {
print(value)
}
Swift currently crashes at runtime with "Fatal error: "Dictionary literal contains duplicate keys" if you have duplicate keys in a dictionary literal. They even don't print actual duplicate keys. This struct collects all the duplicate keys and print them with count.
If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary. The dictionary can not have the same keys, but we can achieve a similar effect by keeping multiple values for a key in the dictionary.
[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .
No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.
Each dictionary key MUST be unique
let people = ["age1":14, "age2":15, "age3":75, "age4":43, "age5":103, "age6":87, "age7":12]
for (key, value) in people {
print(value)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With