Is there a built-in function for converting a string array into a dictionary of strings or do you need to do a loop here?
To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.
If you are going to get elements by positions (index) in the array then array will be quicker (or at least not slower than dictionary). If you are going to search for elements in the array than dictionary will be faster.
Assuming you're using .NET 3.5, you can turn any sequence (i.e. IEnumerable<T>
) into a dictionary:
var dictionary = sequence.ToDictionary(item => item.Key, item => item.Value)
where Key
and Value
are the appropriate properties you want to act as the key and value. You can specify just one projection which is used for the key, if the item itself is the value you want.
So for example, if you wanted to map the upper case version of each string to the original, you could use:
var dictionary = strings.ToDictionary(x => x.ToUpper());
In your case, what do you want the keys and values to be?
If you actually just want a set (which you can check to see if it contains a particular string, for example), you can use:
var words = new HashSet<string>(listOfStrings);
You can use LINQ to do this, but the question that Andrew asks should be answered first (what are your keys and values):
using System.Linq; string[] myArray = new[] { "A", "B", "C" }; myArray.ToDictionary(key => key, value => value);
The result is a dictionary like this:
A -> A B -> B C -> C
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