【发布时间】:2021-08-04 04:01:20
【问题描述】:
我想创建一个 for 循环,将每辆车的许可证号附加到一个空列表“license_numbers = []”中。但是,它只返回一项。有人可以帮我吗?
cars = {'results':{'vehicle': {'specs': {'model': 'a', 'year': '2006'}},
'size': {'length': '4.5m', 'width': '1.7m'},
'colour': 'blue',
'license': '1234'},
'results':{'vehicle': {'specs': {'model': 'b', 'year': '2008'}},
'size': {'length': '3.5m', 'width': '1.2m'},
'colour': 'red',
'license': '5678'}}
我已经尝试了以下内容,但是当我希望返回 (['1234'], ['5678']) 时,我只会返回 ['1234'] :
license_numbers=[]
for x in cars:
license_numbers.append(cars['results']['license'])
谢谢!
【问题讨论】:
-
您的字典中有重复的键
results- 这在 Python 中是不可能的。 -
"但是,它只返回一项" 是的,因为
cars仅包含一项。试着打印出来看看。如果您不明白为什么,请查看教程。
标签: python dictionary for-loop nested append