Python - 使用列表项填充字典

时间:2016-11-06 02:11:07

标签: python dictionary

如果以这种方式创建字典:

output = {'playlist': {}}

有这样的list

tracks = [u'No Surprises', u'Oceans', u'Up in Flames']

count = 0

我想将playlisttracks填充为keys 0output = {'playlist': { 'No Surprises': 0, 'Oceans': 0, 'Up in Flames': 0}} ,如下所示:

{{1}}

我该怎么做?

4 个答案:

答案 0 :(得分:1)

>>> output['playlist'] = dict(zip(tracks, [value for i in tracks]))
>>> output
{'playlist': {u'Up in Flames': 0, u'Oceans': 0, u'No Surprises': 0}}

答案 1 :(得分:1)

output = {'playlist':{track: count for track in tracks}}

答案 2 :(得分:1)

晚了将近两年,但这似乎是dict.fromkeys的理想用例:

let appWindow: NSWindow = {
    let w = NSWindow()
    w.setContentSize(NSSize(width: 400, height: 23))
    w.titlebarAppearsTransparent = true
    w.isMovableByWindowBackground = true
    w.backgroundColor =  NSColor.white //Maybe have it gray instead so we can remove this?
    w.setFrameAutosaveName(NSWindow.FrameAutosaveName(rawValue: "myGoodGoodApp"))
    w.makeKeyAndOrderFront(nil)
    w.contentView?.addSubview(gunTrigger)
    return w
}()

答案 3 :(得分:0)

for track in tracks:
    output["playlist"][track] = 0