Python 循环遍历嵌套字典并将结果追加到列表中的For循环
我想创建一个for循环,将每辆车的许可证号附加到一个空列表“license_numbers=[]”中。但是,它只返回一个项目。有人能帮我吗Python 循环遍历嵌套字典并将结果追加到列表中的For循环,python,dictionary,for-loop,nested,append,Python,Dictionary,For Loop,Nested,Append,我想创建一个for循环,将每辆车的许可证号附加到一个空列表“license_numbers=[]”中。但是,它只返回一个项目。有人能帮我吗 cars = {'results':{'vehicle': {'specs': {'model': 'a', 'year': '2006'}}, 'size': {'length': '4.5m', 'width': '1.7m'}, 'colour': '
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'])
谢谢 python中的字典不能有多个相似的键。我认为解决这个问题的一个办法是让一个键保存一个字典列表,就像这样
cars = {'results1':[{'vehicle': {'specs': {'model': 'a', 'year': '2006'}},
'size': {'length': '4.5m', 'width': '1.7m'},
'colour': 'blue',
'license': '1234'},
{'vehicle': {'specs': {'model': 'b', 'year': '2008'}},
'size': {'length': '3.5m', 'width': '1.2m'},
'colour': 'red',
'license': '5678'}]}
有了这个,我们可以很容易地使用列表理解来收集每个许可证
license = [car.get('license') for car in cars['results1']]
输出
['1234', '5678']
您的字典中有重复的key
results
,这在Python中是不可能的。“但是,它只返回一项”Yes,因为cars
只包含一项。试着打印出来看看。如果你不明白为什么,请复习教程。