I am wondering if I can get or extract the string name of the Key in a Dictionary
I have seen examples accessing the key from inside a foreach, but I need a single index approach. The index will be decided by random int.
public void rng_head()
{
int rnd_q = Random.Range (1, 5);
int rnd_t = Random.Range (1, 5);
// THIS IS HOW I WOULD GET FROM ARRAY or 2D ARRAY
//string output = head_quality [rnd_q].ToString () + " " + head_type [rnd_t].ToString ();
//string output_id = head_quality [rnd_q].ToString () + " " + head_type [rnd_t].ToString ();
// BUT I WANT TO GET FROM DICTIONARY??
string output = dict_head_quality [rnd_q];
string output_id = dict_head_type [rnd_t];
// dictionary should keep perfectly accurate display name vs id_name
// so when items are generated they have a nice display name, but also
// an exact, lowercase, id name
}
A dictionary does not use index since it is not its initial purpose. A dictionary uses key-value relation. It does not so because items are not stored continuously in memory. You have one reference which knows where all items are. But none is first or last. Like when you look in the fridge, you know the eggs are on the door top shelves and the vegetables are on the bottom drawer but which is first then?
You could build one with int,object relation where the int is the key and works as an index. It would be like a list with non continuous indexes.
Your case looks like you should think of list/array instead.
If you really need to store in a dictionary and want to have something random out of it, maybe something like this:
string GetRandomValue(Dictionary<string,string> dict) // Dunno what is your dictionary types...
{
int rnd = Random.Range (1, 5);
int index = 0;
foreach(var kvp in dict){
index++;
if(index == rnd){
return kvp.Key; // According to question, you are after the key
}
}
return null;
}
You can also index the dictionary values by yourself enveloping the key-value pair you are interested into a KeyValuePair and associating it with an int like so:
Dictionary<int, KeyValuePair<string, int>> indexedDictionary = new Dictionary<int, KeyValuePair<string, int>>
{
{0, new KeyValuePair<string, int>("my entry", 13) },
{1, new KeyValuePair<string, int>("whatever", 5) },
{............}
};
Just use DictionaryHelper<TypeOne, TypeTwo>.GetFromIdx(yourDictionary, index)
namespace Helper
{
public class DictionaryHelper<Tone, Ttwo>
{
public static void AttOrAddToDictionary(Dictionary<Tone, Ttwo> dictionary, Tone key, Ttwo value)
{
if (dictionary.ContainsKey(key)) dictionary[key] = value;
else dictionary.Add(key, value);
}
public static KeyValuePair<Tone, Ttwo> GetFromIdx(Dictionary<Tone, Ttwo> dictionary, int idx)
{
int i = 0;
foreach (var kp in dictionary)
{
if (i == idx) return kp;
}
Debug.LogWarning($"Error! index not found");
return new KeyValuePair<Tone, Ttwo>();
}
}
}