How to get a dictionaries unique key from a nested value?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By easypie

My nested dictionary is as follows;

"itemone" : {"text": "some text", "level": 1},
"itemtwo" : {"text": "more text", "level": 1},
"itemthree" : {"text": "even more text", "level": 2},

What I’d like to do randomly select a dictionary key (parent) that contains a level 1 (child).

:bust_in_silhouette: Reply From: Inces

First make random nr generator and reference it, lets say as var R

 func randomchoice( searchedlevel):
  var tempdict = {}
 for key in nesteddict.keys() :
         if nesteddict[key]["level"] == searchedlevel :
 return tempdict[R.randi_range(0,tempdict.size()-1)]

Good idea. Thank you for the suggestion.

For any beginner like myself looking to do something similar, here’s what I ended up doing.

func get_diff_level_words(level):
    var word_list_dict = {}

    for key in word_dict.keys():
	  if word_dict[key]["level"] == level:
		word_list_dict[key] = word_dict[key]
    return word_list_dict

func get_random_word(level):
    var random_word : String
    var letters : Array

    var level_words = get_diff_level_words(level)
    var word_id = randi() % level_words.size()
    var word_key = level_words.keys()
    random_word = word_key[word_id]

    return random_word

func _ready() -> void:
    # demo purposes only...
    print("OUTPUT = " + str(get_random_word(level)))

easypie | 2021-03-16 18:32