0

I have been making a Python game and need some help. I want to be able to have a user craft a item (I have made this) and some items to take longer. I am not sure how to get the number of seconds to wait from an array.

Example Dictionary:

TimeToCraft = {
                   'missile' : 10,
                   'otherThing' : 100,
              }

Any idea how I could read the number from the dictionary above and input it into a time.sleep() function?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    That isn't an array. It's a _dictionary_. You can find tutorials on how to access values from a dictionary by key. – roganjosh Apr 08 '18 at 13:33
  • ok thanks I'm getting confused between the two. What's the difference? – Leo Cornelius Apr 08 '18 at 13:34
  • You might want to follow some tutorials first, for example, [https://docs.python.org/3/tutorial/](https://docs.python.org/3/tutorial/). – ducminh Apr 08 '18 at 13:36
  • There are lots of differences, it would be best to look into some tutorials on this. In Python, the "list" might be considered as the equivalent of an array in other languages (searching for arrays in the context of python is likely to send you down a more complicated path involving numpy, which isn't relevant here) – roganjosh Apr 08 '18 at 13:37
  • OK thank you I will do some research to quench my thirst for knowledge. :} – Leo Cornelius Apr 08 '18 at 13:39
  • Here you have really good answer which summarizes differences between list, dictionary and set: https://stackoverflow.com/a/3489100/3603682 – machnic Apr 08 '18 at 13:41

3 Answers3

2

Try below :

time.sleep(TimeToCraft['missile'])

or

time.sleep(TimeToCraft['otherThing'])
Rehan Azher
  • 1,340
  • 1
  • 9
  • 17
1

This is a dictionary, not an array - which is good because it is the right data structure.

You do not index the element you want like you would in a list or array, you can merely get it with square bracket ([...]) syntax.

For example:

TimeToCraft['missile']

would return 10.

So once you have the user's entry (let's name this item), just pass the result into a time.sleep call (remember to import time fist).

time.sleep(TimeToCraft[item])

One last thing is to remember to check that item is actually a valid entry in the dictionary.

This can be done with the in operator:

if item in TimeToCraft:
    time.sleep(TimeToCraft[item])
else:
    print('sorry, don't have an entry for that item')
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

To get a value form a dictionary, you use the format:

dictionaryName[key]

In your case, the dictionaryName is TimeToCraft and the key is 'missile' or 'otherThing'.

You would then put the value retrieved from the dictionary into time.sleep() :

time.sleep(TimeToCraft['missile'])
032407
  • 61
  • 3