Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting index of dictionary item based on item.key

Tags:

c#

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?

like image 861
FSm Avatar asked Nov 21 '12 09:11

FSm


People also ask

Does dictionary keys have index in Python?

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.

Can we index a dictionary?

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.


2 Answers

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;
}
like image 79
Dennis Traub Avatar answered Oct 13 '22 08:10

Dennis Traub


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);
like image 26
dylful Avatar answered Oct 13 '22 06:10

dylful