当前位置: 动力学知识库 > 问答 > 编程问答 >

python - py3k: mapping dictionary (string->number) into list (of strings)

问题描述:

Assume we have dictionary that translates strings into numbers.

How to reverse it into list ?

Let assume, we can fill not mapped numbers with empty string ''.

Here example how it works:

>>> dic_into_list({'x':0, 'z':2, 'w':3})

['x', '', 'z', 'w']

网友答案:
d = {'x':0, 'z':2, 'w':3}
lst = [""] * (max(d.values()) + 1)
for k, v in d.items():
    lst[v] = k
print(lst)

prints

['x', '', 'z', 'w']
网友答案:

The simplest way is to flip the dict and then iterate up to the maximum value (now key) in the dict:

original = {'x':0, 'z':2, 'w':3}
d = dict((v, k) for k, v in original.iteritems())
print [d.get(i, '') for i in range(max(d) + 1)]
网友答案:

I share my current solution: (I look for shorter and cleared implementation in other posts):

def dic_into_list(dic):
    maxindex = max([v for i,v in dic.items()])
    dicrev = {num:name for name,num in dic.items()}
    l=[]
    for i in range(0,maxindex+1):
        if i in dicrev:
            l.append(dicrev[i])
        else:
            l.append('')
    return l
分享给朋友:
您可能感兴趣的文章:
随机阅读: