For 循环遍历嵌套字典并将结果附加到列表中

时间:2021-05-13 21:36:31

标签: python dictionary for-loop nested append

我想创建一个 for 循环,将每辆车的许可证号附加到一个空列表“license_numbers = []”中。但是,它只返回一项。有人可以帮我吗?

draw

我已经尝试了以下内容,但只有在我希望返回 (['1234'], ['5678']) 时才返回 ['1234'] :

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'}}

谢谢!

1 个答案:

答案 0 :(得分:1)

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']