如何将字典键返回为字符串值Python

2024-05-18 23:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个初级程序员,我有一个问题。我需要在字典中将键值作为字符串返回。

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

就在这里choice[0]我希望程序将键值返回到字典。然后在它说'skill is: '之后,choice,)是它返回该键值的位置。

我只想把键显示为字符串值,以便在程序中轻松访问。

例如,如果键是“X”,值是“X”,我想让程序吐出。

'your current X skill is x' 

到目前为止,打印功能的结束工作正常。


Tags: to字符串程序you字典iscurrentxp
1条回答
网友
1楼 · 发布于 2024-05-18 23:28:56

假设你有一本字典:d = {'X':'x'}

可以从字典中检索值d['X']

函数keys()将返回字典中的键列表,values()将返回字典中的值列表。如果您不知道键并想要检索任何项,那么可以在由keys()返回的列表中使用索引i。试试这个:

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

您的计划的预期解决方案可以是:

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

相关问题 更多 >

    热门问题