【问题标题】:For loop that iterates through a nested dictionary and appends the results in a list [closed]For循环遍历嵌套字典并将结果附加到列表中[关闭]
【发布时间】: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


【解决方案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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2022-01-13
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    相关资源
    最近更新 更多