首页 > 解决方案 > Python按字母顺序将列表转换为字典

问题描述

例如如何转换列表

['and', 'power', 'car', 'abc', 'pen', 'doctor', 'pig']

按字母顺序到字典

{A 1: 'abc', A 2: 'and', C 1: 'car', D 1: 'doctor', P 1: 'pen', P 2: 'pig', P 3: 'power'}

标签: pythonlistdictionary

解决方案


字典插入现在保留顺序,但如果你使用的是旧版本的 Python,你会想要使用 OrderedDict。

lst = ['and', 'power', 'car', 'abc', 'pen', 'doctor', 'pig']
lst.sort() # in-place

d = {}
i = 1
for item in lst: 
    if item[0].upper() in [k[0] for k in d.keys()]: 
        i += 1 
    else: 
        i = 1 
    d[item[0].upper() + ' ' + str(i)] = item

结果:

In [92]: d
Out[92]: 
{'A 1': 'abc',
 'A 2': 'and',
 'C 1': 'car',
 'D 1': 'doctor',
 'P 1': 'pen',
 'P 2': 'pig',
 'P 3': 'power'}

推荐阅读