Python Dictionary调用Dictionary,但TypeError:字符串索引必须是整数
我想根据调用字典的结果调用另一本字典。但是,有一个错误Python Dictionary调用Dictionary,但TypeError:字符串索引必须是整数,python,dictionary,Python,Dictionary,我想根据调用字典的结果调用另一本字典。但是,有一个错误 >>> dict1 = {1:'apple', 2:'mango', 3:'pear'} >>> dict2 = {'apple': 'jason', 'mango': 'mary', 'pear':'susan'} >>> print(dict1[1]['apple']) Traceback (most recent call last): File "<stdin>"
>>> dict1 = {1:'apple', 2:'mango', 3:'pear'}
>>> dict2 = {'apple': 'jason', 'mango': 'mary', 'pear':'susan'}
>>> print(dict1[1]['apple'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
所需的输出是:jason您需要将第一次查找的返回值传递到第二次查找中:
dict2[dict1[1]]
dict1保存字符串,而不是dict2字典,因此在查找时只需将结果字符串传递给dict2:
>>> dict1 = {1:'apple', 2:'mango', 3:'pear'}
>>> dict2 = {'apple': 'jason', 'mango': 'mary', 'pear':'susan'}
>>> dict1[1]
'apple'
>>> dict2['apple']
'jason'
>>> dict2[dict1[1]]
'jason'
请你试试打印口述好吗?@Lafada谢谢你的回复。Martijn Pieters刚刚为这个问题提供了一个明确的解决方案。@Martijn Pieters感谢您的提醒!谢谢Martijin!