python中将list转为dict

最近在项目中经常遇到将list转为dict形式,之前都只会用for循环,取出list中的每个值,update到dict中。

示例1

scrabble_scores = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"), (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]

如何将上面的list拆分成key为字母,value为分数呢?

LETTER_SCORES = {letter: score for score, letters in scrabble_scores for letter in letters.split()}

通过上式处理后,就会形成{"A": 1..........}此类形式。
首先通过split()函数将字母分开,然后取出letters中的letter作为字典的key值,将分值作为value。

示例2

Letter = namedtuple('Letter', 'name amount value')
distribution = [Letter(name='A', amount='9', value='1'), Letter(name='B', amount='2', value='3'), Letter(name='C', amount='2', value='3'), Letter(name='D', amount='4', value='2'), Letter(name='E', amount='12', value='1'), Letter(name='F', amount='2', value='4'), Letter(name='G', amount='3', value='2'), Letter(name='H', amount='2', value='4'), Letter(name='I', amount='9', value='1'), Letter(name='J', amount='1', value='8'), Letter(name='K', amount='1', value='5'), Letter(name='L', amount='4', value='1'), Letter(name='M', amount='2', value='3'), Letter(name='N', amount='6', value='1'), Letter(name='O', amount='8', value='1'), Letter(name='P', amount='2', value='3'), Letter(name='Q', amount='1', value='10'), Letter(name='R', amount='6', value='1'), Letter(name='S', amount='4', value='1'), Letter(name='T', amount='6', value='1'), Letter(name='U', amount='4', value='1'), Letter(name='V', amount='2', value='4'), Letter(name='W', amount='2', value='4'), Letter(name='X', amount='1', value='8'), Letter(name='Y', amount='2', value='4'), Letter(name='Z', amount='1', value='10')]

如何将上面的distribution中的name和value转换成dict形式?

  1. 首先可以先将name和value值分别放到两个list中,可以通过下面代码实现:
names = [letter.name for letter in distribution]
values = [int(letter.value) for letter in distribution]
  1. 然后可以通过zip()函数将name和value一一对应起来:
zip(names, values)


for i in zip(names, values):
    print(i)

通过循环打印可以发现,name和value已经一一对应上了。

  1. 最后将得到的由元组组成的list直接转为dict,在这边只需要直接用dict()函数即可。所以,实现上述功能需求,只需要下面一行代码:
LETTER_SCORES = dict(zip(
        [letter.name for letter in distribution],
        [int(letter.value) for letter in distribution]
    ))

得到的结果为:

{'A': 1, 'B': 3, 'C': 3, 'D': 2, 'E': 1, 'F': 4, 'G': 2, 'H': 4, 'I': 1, 'J': 8, 'K': 5, 'L': 1, 'M': 3, 'N': 1, 'O': 1, 'P': 3, 'Q': 10, 'R': 1, 'S': 1, 'T': 1, 'U': 1, 'V': 4, 'W': 4, 'X': 8, 'Y': 4, 'Z': 10}

你可能感兴趣的:(python3.x)