我有一个字典,看起来像这样存储在一个变量bookR
{'User-ID': '2345667', 'ISBN': '265838929355X', 'Rating': '0'}
{'User-ID': '2345635', 'ISBN': '3456477588844', 'Rating': '5'}
{'User-ID': '2345632', 'ISBN': '9890876776388', 'Rating': '4'}
{'User-ID': '2767888', 'ISBN': '2234566663200', 'Rating': '7'}
我想提取两个并将它们存储在不同的变量中,作为userA和userB
我已经试过了,但是它给出了keyerror代码
print(bookR)
userA = bookR[1]
userB = bookR[4]
print(userA)
print(userB)
但是我需要的结果是
print(userA)
output: {'User-ID': '2345667', 'ISBN': '265838929355X', 'Rating': '0'}
print(userB)
output:{'User-ID': '2767888', 'ISBN': '2234566663200', 'Rating': '7'}
我认为这就是你想要做的:
- 每个字典形成一个项
bookR
列表中
bookR = [{'User-ID': '2345667', 'ISBN': '265838929355X', 'Rating': '0'},
{'User-ID': '2345635', 'ISBN': '3456477588844', 'Rating': '5'},
{'User-ID': '2345632', 'ISBN': '9890876776388', 'Rating': '4'},
{'User-ID': '2767888', 'ISBN': '2234566663200', 'Rating': '7'}]
userA = bookR[0]
userB = bookR[3]
print("user A:", userA)
print("user B:", userB)
输出:
user A: {'User-ID': '2345667', 'ISBN': '265838929355X', 'Rating': '0'}
user B: {'User-ID': '2767888', 'ISBN': '2234566663200', 'Rating': '7'}
注意:
list使用零索引…这意味着第一个项目在索引0