python list转dict_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'

你可能感兴趣的:(python,list转dict)