0 votes

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).

Godot version 3.2.2
in Engine by (15 points)

1 Answer

+1 vote
Best answer

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)]
by (5,649 points)
selected by

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)))
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.