setdefaultで辞書に無いキーと値をセットする[Python]

7月 25, 2020

name_list = ["Taro", "Jiro", "Saburo"]
d = {}

for name in name_list:
    len_name = len(name)
    head_name = name[0]
    d.setdefault(name, ()).append((len_name, head_name))

>> {'Jiro': [[4, 'J']], 'Saburo': [[6, 'S']], 'Taro': [[4, 'T']]}

UncategorizedPython

Posted by vastee