循环遍历字典列表以获取某个键

2024-06-25 23:38:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想循环浏览字典列表(位置)(家庭、工作)以及橙子是否<;1,然后将该字典添加到空列表(存储)。我该怎么做?下面是我的代码设置:

主页={ “橙子”:0, “苹果”:2, “香蕉”:1 } 工时={ “橙子”:1, “苹果”:0, “香蕉”:4 }你知道吗

地点=[家,工作]

存储=[]


Tags: 代码lt苹果列表字典家庭主页地点
1条回答
网友
1楼 · 发布于 2024-06-25 23:38:33

这将使用列表理解来完成。它迭代字典列表locations,并测试每个字典的'orange'键的值:

Home = { 'oranges': 0, 'apples': 2, 'bananas': 1 }
Work = { 'oranges': 1, 'apples': 0, 'bananas': 4 }
locations = [Home, Work]

store = [d for d in locations if 'oranges' in d and d.get('oranges') < 1]

>>> store
[{'apples': 2, 'oranges': 0, 'bananas': 1}]

注意不要包含没有'orange'作为键的字典

注意,应该使用小写变量名,如homework

相关问题 更多 >