python - 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'])
谢谢!
解决方案
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']
推荐阅读
- python - 推断字段分隔文件信息的库
- c - 如何知道何时需要刷新缓冲区?
- php - php用另一个字符串掩盖字符串
- python - 从 init.d 脚本运行时,Virtualenv 库在 python 脚本中错误链接,但在正常运行时没有
- react-native - display webview in card (react native)
- angular - Angular:将参数传递给 this.http.get()
- c - 信号报警过早失效
- lambda - 如何为 lambda 或 java8 制作流程图?
- twitter-bootstrap - Bootstrap 4.1:使用 scrollspy 添加附加辅助侧边栏导航
- python - python中的牛顿法检查