从具有部分索引的字典创建值列表:值

时间:2015-12-23 11:17:13

标签: python list dictionary

我想将index:value的字典转换为包含这些值的列表。对于未出现在字典中的索引,可以使用0。 例如:字典:{1:1, 5:5, 6:6, 7:7, 10:10} 到列表[1,0,0,0,5,6,7,0,0,10]

我正在使用此代码:

for index in xrange(SIZE):
    try:
        list.append(dict[index])
    except KeyError:
        list.append(0)

有更多的pythonic方式吗?没有使用例外? 谢谢, NIV

2 个答案:

答案 0 :(得分:2)

只需使用字典get()方法:

for index in xrange(SIZE):    
    L.append(D.get(index, 0))

此外,为变量而不是listdict选择其他名称,以避免与Python的built-ins命名冲突。

答案 1 :(得分:2)

列表理解

这是列表理解的好选择:

>>> indices = {1:1, 5:5, 6:6, 7:7, 10:10}
>>> SIZE = max(indices.keys()) + 1
>>> [indices.get(index, 0) for index in range(SIZE)]
[0, 1, 0, 0, 0, 5, 6, 7, 0, 0, 10]

变异

if表达式的版本有点长:

[indices[index] if index in indices else 0 for index in range(SIZE)]

速度

get的版本有点慢:

%timeit [indices.get(index, 0) for index in range(SIZE)]
100000 loops, best of 3: 4.35 µs per loop

%timeit [indices[index] if index in indices else 0 for index in range(SIZE)]
100000 loops, best of 3: 3.58 µs per loop