How can I find the index of an element of a dictionary based on the element key? I'm using the following code to go through the dictionary:
foreach (var entry in freq)
{
var word = entry.Key;
var wordFreq = entry.Value;
int termIndex = ??????;
}
Could anyone help please?
Dictionaries are important data structures in Python that use keys for indexing. They are an unordered sequence of items (key-value pairs), which means the order is not preserved. The keys are immutable.
Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
There is no concept of an index in a Dictionary
. You can't rely on any order of items inside the Dictionary
. The OrderedDictionary
might be an alternative.
var freq = new OrderedDictionary<string, int>();
// ...
foreach (var entry in freq)
{
var word = entry.Key;
var wordFreq = entry.Value;
int termIndex = GetIndex(freq, entry.Key);
}
public int GetIndex(OrderedDictionary<string, object> dictionary, string key)
{
for (int index = 0; index < dictionary.Count; index++)
{
if (dictionary.Item[index] == dictionary.Item[key])
return index; // We found the item
}
return -1;
}
This might work and this is probably not the most efficient way of doing this. Also im not sure why you would want something like this.
Int termIndex = Array.IndexOf(myDictionary.Keys.ToArray(), someKey);
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