简体   繁体   中英

how to return a dictionary key as a string value Python

I'm a beginner programmer and I have a question. I need to return a key value as a string in a dictionary.

choice = skills[(input('which attribute would you like to access: '))]
print('Testing, choice was in word')
user = None
while user != 0:
    print('\nyour current', choice[0] ,' skill is:', choice,)
    print('you also have', XP,'XP points left to distribute')
    print('''\nWould you like to Add or take away points
0. Go back
1. Add
2. Take away''')

Right where choice[0] I want the program to return the key value to the dictionary. and then after it says 'skill is: ' , choice,) is where it returns the value of that key.

I want to be able to just display the key as a string value for easy access in the program.

So for instance if the key is "X" and the value is "x" I want the program to spit out.

'your current X skill is x' 

so far the end of the print function works fine.

Suppose you have a dictionary as: d = {'X':'x'}

You can retrieve a value from dictionary as d['X']

The function keys() will return a list of keys in dictionary and values() will return list of values in dictionary. And if you don't know the keys and want to retrieve any item, you can use index i in list returned by keys() . Try this:

d = {'X':'x'}
print('\nyour current', d.keys()[0] ,' skill is:', d[d.keys()[0]])

The expected solution of your program can be:

choice = input('which attribute would you like to access: ')
print('\nyour current', skills[choice] ,' skill is:', choice,)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM