I want to use the dictionary in c# combined with a list like this
Dictionary<int, List<int>> Dir = new Dictionary<int, List<int>>();
but I am having trouble with the syntax for adding the keys and values. I thought if I just did something like
Dir.Add(integer1, integer2);
it would add integer1 was the key, and integer2 as the value. Then if I wanted to add to the integer1 key I would do
Dir.Add[interger1].Add(interger3);
I had one more question, I had a foreach loop like this to display the keys
foreach (KeyValuePair<int, List<int>> k in labelsList)
{
Console.WriteLine(k.Key + " "+ k.Value);
}
it displays the keys I expected up to 7, but it doesn't display the value's I wanted it to show, it just displays
1 System.Collections.Generic.List`1[System.Int32]
2 System.Collections.Generic.List`1[System.Int32]
3 System.Collections.Generic.List`1[System.Int32]
4 System.Collections.Generic.List`1[System.Int32]
5 System.Collections.Generic.List`1[System.Int32]
6 System.Collections.Generic.List`1[System.Int32]
7 System.Collections.Generic.List`1[System.Int32]
I have any idea to use a nested foreach like
foreach (KeyValuePair<int, List<int>> k in labelsList)
{
foreach (KeyValuePair<int, List<int>> k in labelsList)
{
Console.WriteLine(k.Key + " " + k.Value);
}
}
but I am unsure of what to put inside the nested foreach to iterate through the list
You have to add the collection into the dictionary before you can start adding values to it. Here is a solution which make one lookup (compared to two if ContainsKey is used). It also adds the list if it's missing.
public class YourClass
{
private Dictionary<int, List<int>> _dictionary = new Dictionary<int, List<int>>();
public void AddItem(int key, int value)
{
List<int> values;
if (!_dictionary.TryGetValue(key, out values))
{
values = new List<int>();
_dictionary.Add(key, values);
}
values.Add(value);
}
public IEnumerable<int> GetValues(int key)
{
List<int> values;
if (!_dictionary.TryGetValue(key, out values))
{
return new int[0];
}
return values;
}
}
When you call Dir.Add(), you need to provide a reference to a List<int> object. Providing an int itself is not right. So you need something like this:
Dir.Add(integer1, new List<int>());
Then you can update that entry like this:
Dir[integer1].Add(integer2);
Dir[integer1].Add(integer3);
Alternatively, you can use the collection initializer syntax:
Dir.Add(integer1, new List<int> { integer2, integer3});
You need to add a List<int> as value. It'll work like this:
if (!Dir.ContainsKey(integer1)) {
Dir.Add(integer1, new List<int>());
}
var list = Dir[integer1];
list.Add(integer2);
First, create an entry for your key integer1, unless you have already done so:
Dir.Add(integer1, new List<int>());
Then, find the right dictionary entry, then add to its value (in this case, your list):
Dir[integer1].Add(integer2);
You will find more entire code snippets in the other answers, if that is what you are looking for.
If you want to add an item, simply use this code
(whereas dic is your Dictionary<Int32, List<Int32>>)
if (dic.ContainsKey(yourKey))
{
dic[yourKey].Add(yourInt);
} else {
dic[yourKey] = new List<int> { yourInt };
}
Related
Im trying to figure out how I can create something similar to a dictionary, but where each key can map to several values.
Basically what I need is to be able to assign multiple values to the same key without knowing in advance how many values each key will correspond to. I also need to be able to add values to an existing key on multiple occasions. It would also be nice if I could detect when a key + value combination already exists.
An example of how the program should work:
list.Add(1,5);
list.Add(3,6);
list.Add(1,7);
list.Add(5,4);
list.Add(1,2);
list.Add(1,5);
This should ideally produce a table like this:
1: 5, 7, 2
3: 6
5: 4
Is there any existing construction in C# that I can use for this or do I have to implement my own class? Implementing the class would probably not be a big problem, but Im a bit short on time so it would be nice if I could use something that already exists.
Quick Solution
As you have already mentioned, a Dictionary would be the best type to use. You can specify both the key type and value type to meet your needs, in your case you want an int key and a List<int> value.
This is easy enough to create:
Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>();
The challenge then comes with how you add records, you cannot simply do Add(key, value) because that will cause conflict which duplicate keys. So you have to first retrieve the list (if it exists) and add to that:
List<int> list = null;
if (dictionary.ContainsKey(key))
{
list = dictionary[key];
}
else
{
list = new List<int>();
dictionary.Add(key, list);
}
list.Add(newValue);
Preferred Solution
This is obviously a few too many lines to use each time you want to add an item, so you would want to throw that into a helper function, or my preference would be to create your own class that extends the functionality of Dictionary. Something like this:
class ListDictionary<T1, T2> : Dictionary<T1, List<T2>>
{
public void Add(T1 key, T2 value)
{
if (this.ContainsKey(key))
{
this[key].Add(value);
}
else
{
List<T2> list = new List<T2>() { value };
this.Add(key, list);
}
}
public List<T2> GetValues(T1 key)
{
if(this.ContainsKey(key))
return this[key];
return null;
}
}
Which you can then use as easy as you originally wanted:
ListDictionary<int, int> myDictionary = new ListDictionary<int, int>();
myDictionary.Add(1,5);
myDictionary.Add(3,6);
//...and so on
Then to get the list of values for your desired key:
List<int> keyValues = myDictionary.GetValues(key);
//check if NULL before using, NULL means the key does not exist
//alternatively you can check if the key exists with if (myDictionary.ContainsKey(key))
You can create a dictionary of Lists quite easily e.g.
Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>()
An Alternative if you have created a list of items and want to separate them into groups with different keys, which serves much the same purpose is the Lookup class.
Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>();
public void AddIfNotExistInDic(int key, int Value) {
List<int> list = null;
if (dictionary.ContainsKey(key)) {
list = dictionary[key];
}
else {
list = new List<int>();
dictionary.Add(key, list);
}
if (!list.Contains(Value)) {
list.Add(Value);
}
}
You can use Dictionary<TKey, TValue>, the TKey would be int and TValue would be List<int>, You can add as many element in List as it grow autmatically.
Dictionary <int, List<int>> dic = new Dictionary<int, List<int>>();
The way you can access the value would change, you can for instance add element in dictionary like
void AddToYourCustomDictionary(int key, int someValue)
{
if(!dic.ContainsKey(key))
{
dic.Add(key, new List<int>());
dic[key].Add(someValue);
}
else
dic[key].Add(someValue); //Adding element in existing key Value pair
}
To access element in Dictionary Key -> value i.e list,
Console.WriteLine(dic[key][indexOfList]);
I've a class like as below:
public class Source
{
...
...
public List<Dictionary<int, int>> blanks { get; set; }
}
I've created an object of this and a Dictionary for it. I filled 'dic' Dictionary. Then, I add this dic to the blanks list.
Source src = new Source();
Dictionary<int, int> dic = new Dictionary<int, int>();
dic.Add(30, 50);
dic.Add(40, 60);
src.blanks.Add(dic);
And I try to access these 'Key' and 'Value' elements. But, I can't.
int a = src.blanks[0].Key;
int b = src.blanks[0].Value;
What can I do to access these elements?
Thanks.
src.blanks[0] is a whole dictionary, not a single KeyValuePair<int,int>. That is why you cannot access a .Key or .Value on it - there are potentially many keys, and many values associated with them.
You can access all key-value pairs in a dictionary at position zero by enumerating them, like this:
foreach (var kvp in src.blanks[0]) {
int a = kvp.Key;
int b = kvp.Value;
Console.WriteLine("Key:{0} Value:{1}", a, b);
}
blanks[0] returns a Dictionary<int, int>, you need to specify key of your item.
src.blanks[0][key]
Or loop through your values:
foreach(var pair in src.blanks[0])
{
int currentKey = pair.Key;
int currentValue = pair.Value;
}
You are trying to access a dictionary in the list which has no Key property. The Keyvaluepairs in a dictionary have keys.
So assuming you want to look into the first dictionary in the list:
Dictionary<int, int> dict = s.blanks[0];
// lookup 30:
int value = dict[30]; // 40
to get the value you should first index the list and then index the dictionary
to get value
int b = (src.blanks[0])[0]
You want something like the following:
var listItem = src.blanks[0];
var dictionaryItem = listItem[0];
var a = dictionaryItem.Key;
var b = dictionaryItem.Value;
Nevertheless, i advice you to get rid of those "nested generics" List<Dictionary<..,..>. You won't be able to distinguish what kind of object you're dealing with if you use these nested structs.
Use other structs that better represent your business logic. For example, you could derive your own class from List
I am trying to search in a dictionary.
I have 2 dictionaries:
Dictionary<int, string> dict = new Dictionary<int, string>()
Dictionary<int, int> temp = new Dictionary<int, int>()
then ive populated this dictionary with:
dict.Add(123, "");
dict.Add(124, ""); //and so on
then i want to loop though this dictionary and recall the key and add that to the other dictionary
for (int i = 0; i < dict.Count; i++)
{
if (dict[i] == "")
{
temp.Add(dict[dict.ElementAt(i).Key],0);
dict[dict.ElementAt(i).Value] = "Moved";
}
}
i shall be doing other things inside this forloop so i cannot change that to a foreach loop. I am trying to check if the value of the Dictionary dict is empty then take the Key and copy the key value to the temp dictionary, but i am getting errors.
Please help :)
the problem im trying to solve is that i want to be able to search the dict dictionary for for a value with "" and take the key and store it in another dictionary temp (which will later on hold a second value). i need to do this in a for-loop as i want to be able to go back by changing the value of i.
i want to be able to use i to select both the key and value from the dict dictionary.
The errors i was getting was simply converting from string to int, i cannot get it to even store the key from dict into an int variable.
You need to put a value in the temp dictionary. I chose 0.
Dictionary<int, string> dict = new Dictionary<int, string>();
Dictionary<int, int> temp = new Dictionary<int, int>();
dict.Add(123, "");
dict.Add(124, ""); //and so on
int[] keys = dict.Keys.ToArray();
for (int i = 0; i < dict.Count; i++)
{
if (dict[keys[i]] == "")
{
temp.Add(keys[i],0);
dict[keys[i]] = "Moved";
}
}
I think this is what you're looking for:
Dictionary<int, string> dict = new Dictionary<int, string>();
List<int> temp = new List<int>();
dict.Add(123, "");
dict.Add(124, ""); //and so on
foreach (int key in dict.Keys.ToList())
{
if (dict[key] == "")
{
temp.Add(key);
dict[key] = "Moved";
}
}
}
*
First, notice temp is a List, not a Dictionary, since you're just adding the keys, no key => value (this can be changed if you can better explain why you need this as a dictionary)...
Second, notice I used dict.Keys to get all the keys in the dictionary. I also used ToList() so it can work in the foreach loop...
are you getting a compile error for the dictionary definition
Dictionary<int, int> temp = new Dictionary<int, temp>(); // int, temp?
if so,
Dictionary<int, int> temp = new Dictionary<int, int>(); // int, int
?
or, you're getting an error with this:
temp.Add(dict[dict.ElementAt(i).Key]);
because you're adding just a key, with no value. it would be something like
temp.Add(i, dict[i]); ?
if you're just using temp to hold the key values, you don't want a Dictionary, you probably HashSet (only keys, no keys+values)
if you explain exactly what you're trying to solve, this is probably something you can do trivially with a single linq statement?
Why is temp a dictionary? I would use a List<int> with all keys of the dictionary with an empty(null?) value.
List<int> keysWithEmptyValuesInDictionary = dict
.Where(kvp => string.IsNullOrEmpty(kvp.Value))
.Select(kvp => kvp.Key)
.ToList();
foreach (int key in keysWithEmptyValuesInDictionary)
{
dict[key] = "moved";
}
I have a set of elements/keys which I'm reading from two different config files. So the keys may be same but with different values associated with each of them.
I want to list them in the sorted order. What can I do ? I tried with SortedList class but it does not allow duplicate keys.
How can I do it?
e.g Lets say I have 3 elements with keys 1,2,3. Then i get one more element having key 2 (but different value). Then I want the new key to get inserted after existing key 2 but before 3. If I againg find an element with key 2, then it should go after most recently added key 2.
Please note than I'm using .NET 2.0
I prefer to use LINQ for this type of thing:
using System.Linq;
...
var mySortedList = myList.Orderby(l => l.Key)
.ThenBy(l => l.Value);
foreach (var sortedItem in mySortedList) {
//You'd see each item in the order you specified in the loop here.
}
Note: you must be using .NET 3.5 or later to accomplish this.
what you need is a Sort function with a custom IComparer. What you have now is the default icomparer when you use sort. this will check on a field value.
When you create a custom IComparer (you do this in you class by implementing the Icomparable interface). what it does is: your object checks itself to every other object in the list you sort.
this is done by a function. (don't worry VS will implementd it when refering your interface
public class ThisObjectCLass : IComparable{
public int CompareTo(object obj) {
ThisObjectCLass something = obj as ThisObjectCLass ;
if (something!= null)
if(this.key.CompareTo(object.key) == 0){
//then:
if .....
}
else if(this.value "is more important then(use some logic here)" something.value){
return 1
}
else return -1
else
throw new ArgumentException("I am a dumb little rabid, trying to compare different base classes");
}
}
read on the links above for better information.
I know I had some troubles understanding this myself in the beginning, so for any extra help add a comment and I will elaborate
I did it by creating a SortedList<int, List<string>>. Whenever I find the duplicate key, I simply insert the value in the existing list associated with the key already present in the SortedList object. This way, I can have list of values for a particular key.
Use your own comparer class!
If your keys in the sorted list are integers, you may use for example this comparer:
public class DegreeComparer : IComparer<int>
{
#region IComparer<int> Members
public int Compare(int x, int y)
{
if (x < y)
return -1;
else
return 1;
}
#endregion
}
To instanciate a new SortedList with int keys and string values use:
var mySortedList = new SortedList<int, string>(new DegreeComparer());
If you don't really care about the sequence of the elements with equal keys, add everything to a list and then sort it by key:
static void Main(string[] args)
{
List<KeyValuePair<int, MyClass>> sortedList =
new List<KeyValuePair<int, MyClass>>() {
new KeyValuePair<int, MyClass>(4, new MyClass("four")),
new KeyValuePair<int, MyClass>(7, new MyClass("seven")),
new KeyValuePair<int, MyClass>(5, new MyClass("five")),
new KeyValuePair<int, MyClass>(4, new MyClass("four-b")),
new KeyValuePair<int, MyClass>(7, new MyClass("seven-b"))
};
sortedList.Sort(Compare);
}
static int Compare(KeyValuePair<int, MyClass> a, KeyValuePair<int, MyClass> b)
{
return a.Key.CompareTo(b.Key);
}
If you really want the items inserted later to be after those inserted earlier, sort them as they are inserted:
class Sorter : IComparer<KeyValuePair<int, MyClass>>
{
static void Main(string[] args)
{
List<KeyValuePair<int, MyClass>> sortedList = new List<KeyValuePair<int, MyClass>>();
Sorter sorter = new Sorter();
foreach (KeyValuePair<int, MyClass> kv in new KeyValuePair<int, MyClass>[] {
new KeyValuePair<int, MyClass>(4, new MyClass("four")),
new KeyValuePair<int, MyClass>(7, new MyClass("seven")),
new KeyValuePair<int, MyClass>(5, new MyClass("five")),
new KeyValuePair<int, MyClass>(4, new MyClass("four-b")),
new KeyValuePair<int, MyClass>(4, new MyClass("four-c")),
new KeyValuePair<int, MyClass>(7, new MyClass("seven-b")) })
{
sorter.Insert(sortedList, kv);
}
for (int i = 0; i < sortedList.Count; i++)
{
Console.WriteLine(sortedList[i].ToString());
}
}
void Insert(List<KeyValuePair<int, MyClass>> sortedList, KeyValuePair<int, MyClass> newItem)
{
int newIndex = sortedList.BinarySearch(newItem, this);
if (newIndex < 0)
sortedList.Insert(~newIndex, newItem);
else
{
while (newIndex < sortedList.Count && (sortedList[newIndex].Key == newItem.Key))
newIndex++;
sortedList.Insert(newIndex, newItem);
}
}
#region IComparer<KeyValuePair<int,MyClass>> Members
public int Compare(KeyValuePair<int, MyClass> x, KeyValuePair<int, MyClass> y)
{
return x.Key.CompareTo(y.Key);
}
#endregion
}
Or you could have a sorted list of lists:
static void Main(string[] args)
{
SortedDictionary<int, List<MyClass>> sortedList = new SortedDictionary<int,List<MyClass>>();
foreach (KeyValuePair<int, MyClass> kv in new KeyValuePair<int, MyClass>[] {
new KeyValuePair<int, MyClass>(4, new MyClass("four")),
new KeyValuePair<int, MyClass>(7, new MyClass("seven")),
new KeyValuePair<int, MyClass>(5, new MyClass("five")),
new KeyValuePair<int, MyClass>(4, new MyClass("four-b")),
new KeyValuePair<int, MyClass>(4, new MyClass("four-c")),
new KeyValuePair<int, MyClass>(7, new MyClass("seven-b")) })
{
List<MyClass> bucket;
if (!sortedList.TryGetValue(kv.Key, out bucket))
sortedList[kv.Key] = bucket = new List<MyClass>();
bucket.Add(kv.Value);
}
foreach(KeyValuePair<int, List<MyClass>> kv in sortedList)
{
for (int i = 0; i < kv.Value.Count; i++ )
Console.WriteLine(kv.Value[i].ToString());
}
}
I'm not sure if you can use List initializers in .NET 2.0 like I did in the first example above, but I'm sure you know how to populate a list with data.
.NET doesn't have huge support for stable sorts (meaning that equivalent elements maintain their relative order when sorted). However, you can write your own stable-sorted-insert using List.BinarySearch and a custom IComparer<T> (that returns -1 if the key is less than or equal to the target, and +1 if greater).
Note that List.Sort is not a stable sort, so you'd either have to write your own stable quicksort routine or just use insertion sort to initially populate the collection.
did you contemplate the NameValueCollection class as it allows you to store multiple values per key? you could for example have the following:
NameValueCollection nvc = new NameValueCollection();
nvc.Add("1", "one");
nvc.Add("2", "two");
nvc.Add("3", "three");
nvc.Add("2", "another value for two");
nvc.Add("1", "one bis");
and then to retrieve the values you could have:
for (int i = 0; i < nvc.Count; i++)
{
if (nvc.GetValues(i).Length > 1)
{
for (int x = 0; x < nvc.GetValues(i).Length; x++)
{
Console.WriteLine("'{0}' = '{1}'", nvc.GetKey(i), nvc.GetValues(i).GetValue(x));
}
}
else
{
Console.WriteLine("'{0}' = '{1}'", nvc.GetKey(i), nvc.GetValues(i)[0]);
}
}
which give the output:
'1' = 'one'
'1' = 'one bis'
'2' = 'two'
'2' = 'another value for two'
'3' = 'three'
In .NET 2.0 you can write :
List<KeyValuePair<string, string>> keyValueList = new List<KeyValuePair<string, string>>();
// Simulate your list of key/value pair which key could be duplicate
keyValueList.Add(new KeyValuePair<string,string>("1","One"));
keyValueList.Add(new KeyValuePair<string,string>("2","Two"));
keyValueList.Add(new KeyValuePair<string,string>("3","Three"));
// Here an entry with duplicate key and new value
keyValueList.Add(new KeyValuePair<string, string>("2", "NEW TWO"));
// Your final sorted list with one unique key
SortedList<string, string> sortedList = new SortedList<string, string>();
foreach (KeyValuePair<string, string> s in keyValueList)
{
// Use the Indexer instead of Add method
sortedList[s.Key] = s.Value;
}
Output :
[1, One]
[2, NEW TWO]
[3, Three]
How about this
SortedList<string, List<string>> sl = new SortedList<string, List<string>>();
List<string> x = new List<string>();
x.Add("5");
x.Add("1");
x.Add("5");
// use this to load
foreach (string z in x)
{
if (!sl.TryGetValue(z, out x))
{
sl.Add(z, new List<string>());
}
sl[z].Add("F"+z);
}
// use this to print
foreach (string key in sl.Keys)
{
Console.Write("key=" + key + Environment.NewLine);
foreach (string item in sl[key])
{
Console.WriteLine(item);
}
}
I had a similar issue where I was designing a game similar to the concept of a Chess game where you have the computer make a move. I needed to have the possibility of multiple pieces being able to make a move and thus I needed to have multiple Board-States. Each BoardState needed to be ranked based on the position of the pieces. For argument sake and simplicity, say my game was Noughts and Crosses and I was Noughts and the Computer was Crosses. If the board-state was showing 3 in a row of Noughts then this is the best state for me, if it shows 3 in a row of Crosses then this is the worst state for me and best for the computer. There are other states during the game that are more favourible to one or the other and furthermore there are muliplte states that result in a Draw, so how do I go about ranking it when there are equal rank scores. This is what I came up with (apologise in advance if you are not a VB programmer).
My comparer class:
Class ByRankScoreComparer
Implements IComparer(Of BoardState)
Public Function Compare(ByVal bs1 As BoardState, ByVal bs2 As BoardState) As Integer Implements IComparer(Of BoardState).Compare
Dim result As Integer = bs2.RankScore.CompareTo(bs1.RankScore) 'DESCENDING order
If result = 0 Then
result = bs1.Index.CompareTo(bs2.Index)
End If
Return result
End Function
End Class
My declarations:
Dim boardStates As SortedSet(Of BoardState)(New ByRankScoreComparer)
My Board-State implementation:
Class BoardState
Private Shared BoardStateIndex As Integer = 0
Public ReadOnly Index As Integer
...
Public Sub New ()
BoardStateIndex += 1
Index = BoardStateIndex
End Sub
...
End Class
As you can see RankScores are maintained in descending order and any 2 states having the same rank-score the later state goes to the bottom as it will always have a greater assigned Index and thus this allows duplicates. I can also safely call boardStates.Remove(myCurrentBoardState) which also uses the comparer and the comparer must return a 0 value in order to locate the objected to be deleted.
How do I enumerate a dictionary?
Suppose I use foreach() for dictionay enumeration. I can't update a key/value pair inside foreach(). So I want some other method.
To enumerate a dictionary you either enumerate the values within it:
Dictionary<int, string> dic;
foreach(string s in dic.Values)
{
Console.WriteLine(s);
}
or the KeyValuePairs
foreach(KeyValuePair<int, string> kvp in dic)
{
Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value);
}
or the keys
foreach(int key in dic.Keys)
{
Console.WriteLine(key.ToString());
}
If you wish to update the items within the dictionary you need to do so slightly differently, because you can't update the instance while enumerating. What you'll need to do is enumerate a different collection that isn't being updated, like so:
Dictionary<int, string> newValues = new Dictionary<int, string>() { 1, "Test" };
foreach(KeyValuePair<int, string> kvp in newValues)
{
dic[kvp.Key] = kvp.Value; // will automatically add the item if it's not there
}
To remove items, do so in a similar way, enumerating the collection of items we want to remove rather than the dictionary itself.
List<int> keys = new List<int>() { 1, 3 };
foreach(int key in keys)
{
dic.Remove(key);
}
In answer to the problem "I can't update value/key inside foreach()", you cannot modify a collection while enumerating it. I would approach this by making a copy of the Keys collection:
Dictionary<int,int> dic=new Dictionary<int, int>();
//...fill the dictionary
int[] keys = dic.Keys.ToArray();
foreach (int i in keys)
{
dic.Remove(i);
}
Foreach. There are three ways: You can enumerate over the Keys property, over the Values property or over the dictionary itself which is an enumerator of KeyValuePair<TKey, TValue>.
I just answered the same (updated) question for lists, so here's the same thing for dictionaries.
public static void MutateEach(this IDictionary<TKey, TValue> dict, Func<TKey, TValue, KeyValuePair<TKey, TValue>> mutator)
{
var removals = new List<TKey>();
var additions = new List<KeyValuePair<TKey, TValue>>();
foreach (var pair in dict)
{
var newPair = mutator(pair.Key, pair.Value);
if ((newPair.Key != pair.Key) || (newPair.Value != pair.Value))
{
removals.Add(pair.Key);
additions.Add(newPair);
}
}
foreach (var removal in removals)
dict.Remove(removal);
foreach (var addition in additions)
dict.Add(addition.Key, addition.Value);
}
Note that we have to do the updates outside the loop, so we aren't modifying the dictionary as we enumerate it. Also this detects clashes caused by making two keys the same - it will throw (due to the use of Add).
Example - make all keys lowercase and trim all values, with a Dictionary<string, string>:
myDict.MutateEach(key => key.ToLower(), value => value.Trim());
If the keys are not unique when made lowercase, this will throw.