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爲分數呢?code

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

經過上式處理後,就會造成{"A": 1..........}此類形式。
首先經過split()函數將字母分開,而後取出letters中的letter做爲字典的key值,將分值做爲value。ip

示例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形式?it

  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已經一一對應上了。io

  1. 最後將獲得的由元組組成的list直接轉爲dict,在這邊只須要直接用dict()函數便可。因此,實現上述功能需求,只須要下面一行代碼:
LETTER_SCORES = dict(zip(
        [letter.name for letter in distribution],
        [int(letter.value) for letter in distribution]
    ))

獲得的結果爲:for循環

{'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}
相關文章
相關標籤/搜索