Listing variables with dictionary definitions | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Listing variables with dictionary definitions

I've just started to learn how to code and I chose Python. I don't fully know what I'm doing so I'll try and explain it as best as possible. In a test text based game I made, a player travels to towns and buys various stuff. I have different lists of things in the shop and dictionaries for each items stats. However when I tell the computer to display the items it just shows all the dictionary info for each item because they are variables. What is the most efficient way to display the name of the item

23rd Dec 2016, 2:17 AM
Nate Plate
Nate Plate - avatar
3 Answers
+ 4
Without your code it's difficult to guess what you need ^^ If you iterate over the dict to print each key names, you can use the [ for key, value in dict.iteritems() ] loop structure... Else, if you know how to access to a particular value, then you know its key name: key="mykey" print(mydict[key]) So, just print(key)... And if you access with a litteral string, you know also the key, wich is hardcoding: print(mydict["mykey"]) print("mykey"]
23rd Dec 2016, 2:48 AM
visph
visph - avatar
+ 2
You can get a specific value from a dict if that is what you're asking for. Something like print(item['name']) should work.
23rd Dec 2016, 2:46 AM
James Durand
James Durand - avatar
0
Thanks, didn't get it at first but now I do
24th Dec 2016, 4:17 PM
Nate Plate
Nate Plate - avatar