从字典列表中删除某些键

时间:2017-03-26 05:55:04

标签: python list dictionary

import SpriteKit
import PlaygroundSupport

public class GameScene: SKScene {
    let node: SKNode

    init(nodeToRotate: SKNode) {
        self.node = nodeToRotate
        super.init(size: CGSize(width: 500, height: 400))
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    public override func update(_ currentTime: TimeInterval) {
        let turnAngle = 9.0
        node.zRotation = node.zRotation + CGFloat(turnAngle / (180.0/Double.pi))
    }
}

let square = SKShapeNode(rectOf: CGSize(width: 80, height: 80))
square.fillColor = .purple
square.strokeColor = .purple
square.position = CGPoint(x: 250, y: 200)

let circle = SKShapeNode(circleOfRadius: 30)
circle.fillColor = .orange
circle.strokeColor = .orange
circle.position = CGPoint(x: 0, y: 0)
circle.yScale = 0.7
square.addChild(circle)

let scene = GameScene(nodeToRotate: square)
scene.addChild(square)

let view = SKView(frame: CGRect(origin: .zero, size: CGSize(width: 500, height: 400)))
view.presentScene(scene)

PlaygroundPage.current.liveView = view

在上面的词典列表中,我只想保留这些词典。此列表中的键:[{'YEAR': 2016.0, 'DOY': 310.0, 'temperature': 12.55, 'min_temp': 10.61, 'max_temp': 14.19, 'field_id': 1, 'date': Timestamp('2016-11-05 00:00:00')}, {'YEAR': 2016.0, 'DOY': 311.0, 'temperature': 14.89, 'min_temp': 12.6, 'max_temp': 17.49, 'field_id': 1, 'date': Timestamp('2016-11-06 00:00:00')}]

Filter dict to contain only certain keys?开始,我可以将dict过滤为仅限某些键:

['YEAR', 'temperature']

- 更新: 如果词典中不存在来自new_dict = { your_key: old_dict[your_key] for your_key in your_keys } 的键

,则soln也应该有效

2 个答案:

答案 0 :(得分:2)

list comprehension与字典理解相结合,以获得字典列表:

class EventDateRangeManager(models.Manager):

    def occurring_in_day(self, year, month, day):
        try:
            picked_date = datetime.date(int(year), int(month), int(day))
        except (TypeError, ValueError):
            return an empty query set here

        return self.get_queryset().filter(
            start_day__lte=picked_date,
            end_day__gte=picked_date,
        )
根据问题更改

更新

要使字典理解能够工作,即使字典中不存在your_key的键,也要使用>>> lst = [{'YEAR': 2016.0, 'DOY': 310.0, 'temperature': 12.55, 'min_temp': 10.61, 'max_temp': 14.19, 'field_id': 1, 'date': Timestamp('2016-11-05 00:00:00')}, {'YEAR': 2016.0, 'DOY': 311.0, 'temperature': 14.89, 'min_temp': 12.6, 'max_temp': 17.49, 'field_id': 1, 'date': Timestamp('2016-11-06 00:00:00')}] >>> keys_to_retain = ['YEAR', 'temperature'] >>> [{key: d[key] for key in keys_to_retain} for d in lst] [{'YEAR': 2016.0, 'temperature': 12.55}, {'YEAR': 2016.0, 'temperature': 14.89}] 子句:

if

或者,如果您希望结果dicitonaries具有缺失键的默认值,则可以使用[{key: d[key] for key in keys_to_retain if key in d} for d in lst] ^^^^^^^^^^^ 使用默认值而不是dict.get

dict[..]

答案 1 :(得分:1)

使用pop

的另一个解决方案
PATH

结果

TESSDATA_PREFIX