Python CodeLab dictionary

This question already has an answer here:

  • How to merge two dictionaries in a single expression? 48 answers

  • 你可能需要使用defaultdict - 这里nafta被用作三个关键字( canadian_capitals, mexican_capitals, us_capitals ),如下所示 -

    >>>dic = defaultdict(list)
    >>>lst = ['nafta1', 'canadian_capitals1', 'mexican_capitals1', 'us_capitals1', 'nafta2', 'canadian_capitals2', 'mexican_capitals2', 'us_capitals2']
    >>>grouped_lst = [lst[i:i+4] for i in range(0,len(lst),4)]
    >>>[['nafta1', 'canadian_capitals1', 'mexican_capitals1', 'us_capitals1'], ['nafta2', 'canadian_capitals2', 'mexican_capitals2', 'us_capitals2']]
    >>>for i in grouped_lst:dic[i[0]]=i[1:]
    >>>dic.items()
    >>>[('nafta1', ['canadian_capitals1', 'mexican_capitals1', 'us_capitals1']), ('nafta2', ['canadian_capitals2', 'mexican_capitals2', 'us_capitals2'])]
    >>>for i in dic.keys():print dic[i]
    >>>['canadian_capitals1', 'mexican_capitals1', 'us_capitals1']
    ['canadian_capitals2', 'mexican_capitals2', 'us_capitals2']
    
    链接地址: http://www.djcxy.com/p/17568.html

    上一篇: 无法在Python中合并两个字典

    下一篇: Python CodeLab词典