首页 > 解决方案 > 使用 Python 将 dict 解析为特定的列表格式

问题描述

说我有以下字典

{'red':'boop','white':'beep','rose':'blip'}

我想把它放到这样的列表中

['red','boop','end','white','beep','rose','blip','end']

要放置在列表前面的键/值是输入。

所以我本质上我想要[first_key, first_value,end, .. rest of the k/v pairs..,end]

我写了一个蛮力方法,但我觉得有一种更 Pythonic 的方式来做它(也因为一旦实现该片段将使我的代码 O(n^2) )

for item in lst_items    
    data_lst = []
    for key, value in item.iteritems():
        data_lst.append(key)
        ata_lst.append(value)
    #insert 'end' at the appropiate indeces
 #more code ...

任何pythonic方法?

标签: pythonpython-2.7listdictionary

解决方案


下面依赖于itertools.chain.from_iterable将项目展平为单个列表。我们从 中提取前两个值chain,然后使用它们来构建一个新列表,我们用其余的值扩展该列表。

from itertools import chain

def ends(d):
    if not d:
        return []
    c = chain.from_iterable(d.iteritems())
    l = [next(c), next(c), "end"]
    l.extend(c)
    l.append("end")
    return l

ends({'red':'boop','white':'beep','rose':'blip'})
# ['rose', 'blip', 'end', 'white', 'beep', 'red', 'boop', 'end']

如果您首先知道您想要的键,并且不关心其余的,我们可以使用惰性求值的生成器表达式将其从展平列表中删除。

def ends(d, first):
    if not d:
        return []
    c = chain.from_iterable((k, v) for k, v in d.iteritems() if k != first)
    l = [first, d[first], "end"]
    l.extend(c)
    l.append("end")
    return l

ends({'red':'boop','white':'beep','rose':'blip'}, 'red')
# ['red', 'boop', 'end', 'rose', 'blip', 'white', 'beep', 'end']

推荐阅读