首页 > 解决方案 > For 循环遍历嵌套字典并将结果附加到列表中

问题描述

我想创建一个 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'])

谢谢!

标签: pythondictionaryfor-loopnestedappend

解决方案


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

推荐阅读