我正在使用python遍历字典。在python命令行解释器中运行与在程序文件中运行的相同行时,得到的结果不同。
这是我要遍历的字典:
[
{
'UserName': 'tdunphy',
'SSHPublicKeyId': 'APKA5AODVC64ZX5MQAL3',
'Status': 'Active',
'UploadDate': datetime.datetime(2019, 4, 24, 14, 55, 31, tzinfo=tzutc())
},
{
'UserName': 'tdunphy',
'SSHPublicKeyId': 'APKA5AODVC64XOP4SW6S',
'Status': 'Active',
'UploadDate': datetime.datetime(2019, 4, 24, 15, 3, 52, tzinfo=tzutc())
},
{
'UserName': 'tdunphy',
'SSHPublicKeyId': 'APKA5AODVC642ZRWMQWE',
'Status': 'Active',
'UploadDate': datetime.datetime(2019, 4, 24, 15, 4, 19, tzinfo=tzutc())
}
]
在命令行中,我进入
ssh_keys_list = (client.list_ssh_public_keys(UserName=user_name)['SSHPublicKeys'])
for ssh_key in ssh_keys_list:
ssh_key_id = ssh_key['SSHPublicKeyId']
print(ssh_key_id)
然后我得到这个结果:
APKA5AODVC64ZX5MQAL3
APKA5AODVC64XOP4SW6S
APKA5AODVC642ZRWMQWE
但是,如果我从程序中运行它,则会出现错误:
ssh_key_id = ssh_key['SSHPublicKeyId']
TypeError: string indices must be integers
两者之间的行是相同的,我从命令行解释器复制/粘贴到文件中并运行它。为什么会有差异?