Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array to dictionary with value as index of the item and key as the item itself

I have an array such as -

arr[0] = "Name"; arr[1] = "Address"; arr[2] = "Phone"; ... 

I want to create a Dictionary<string, int> such that the array values will be the dictionary keys and the dictionary values will be the index, so that I can get the index of a column by querying its name in O(1). I know this should be fairly simple, but I can't get my head around it.

I tried -

Dictionary<string, int> myDict = arr.ToDictionary(x => x, x => indexOf(x)) 

however, this returns -

{(Name, 0), (Address, 0), (Phone, 0),...} 

I know this happens because it is storing the index of the first occurence, but that's not what I'm looking to do.

like image 828
neuDev33 Avatar asked Mar 06 '13 16:03

neuDev33


People also ask

How do you pass an array to a dictionary in Python?

To convert a dictionary to an array in Python, use the numpy. array() method, and pass the dictionary object to the np. array() method as an argument and it returns the array.

Can a dictionary key be an array?

The Dictionary object is used to hold a set of data values in the form of (key, item) pairs. A dictionary is sometimes called an associative array because it associates a key with an item. The keys behave in a way similar to indices in an array, except that array indices are numeric and keys are arbitrary strings.

How do I turn an array into a map?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.


1 Answers

You can use the overload of Select which includes the index:

var dictionary = array.Select((value, index) => new { value, index })                       .ToDictionary(pair => pair.value, pair => pair.index); 

Or use Enumerable.Range:

var dictionary = Enumerable.Range(0, array.Length).ToDictionary(x => array[x]); 

Note that ToDictionary will throw an exception if you try to provide two equal keys. You should think carefully about the possibility of your array having two equal values in it, and what you want to happen in that situation.

I'd be tempted just to do it manually though:

var dictionary = new Dictionary<string, int>(); for (int i = 0; i < array.Length; i++) {     dictionary[array[i]] = i; } 
like image 102
Jon Skeet Avatar answered Sep 21 '22 06:09

Jon Skeet