Python CodeLab词典

这个问题在这里已经有了答案:

  • 如何在单个表达式中合并两个字典? 48个答案

  • 你可能需要使用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/17567.html

    上一篇: Python CodeLab dictionary

    下一篇: python: merging dictionaries by identical value of key