Is it possible to shuffle a Dictionary? Any other shuffleable data structure we can access both by key and index?
I can access the dictionary by it's index doing:
myDictionary.Keys[0];
myDictionary.Keys[1];
I also can access a value of the dictionary by it's key:
myDiccionary[myKey];
Here you can find answer about how to shuffle a list, but not a dictionary. I think a solution could be creating an array with the keys I want to store afterwards within a dictionary. Then shuffle that list. Finally build the dictionary as follows:
foreach (int shuffledKeys in shuffledKeysList) {
myDiccionary.Add(shuffledKey, GetValueFromMy(shuffledKey));
}
I guess that should give me a shuffled dictionary as hopefully the access order by index will depend on the order the tuples (key, value) have been added to the dictionary. Does it work like that? Any other better implementation?
Answer by chelder · Jun 06, 2016 at 07:09 PM
I would swear accessing by the index was working, but not anymore. Anyway, the following solution is working well:
I have created a list of keys. Then I shuffle that list. So if we have:
List<string> keys;
Dictionary<string, anotherType> myDictionary;
InitDictionaryAndKeys();
keys.myShuffleMethod();
Then we can access to the item in the third position typing:
anotherType myValue = myDictionary[keys[2]];
Answer by sushanta1991 · Aug 27, 2021 at 11:55 AM
Check this post, it has an example showing how you can shuffle a dictionary and a list also.
https://sushanta1991.blogspot.com/2021/08/how-to-shuffle-or-randomize-order-in.html
I know this post is old but i want others to find a solution.
Your answer
Follow this Question
Related Questions
Question about "shuffling" a deck of cards 2 Answers
Need help with specifics in Random.Range 1 Answer
How to make RANDOM COLOR on shader 1 Answer
Randonly Losing reference to GameObject from prefab 1 Answer
Animations On Random isn't working 0 Answers