问题是 这就是我到目前为止所做的:
dict(nafta_capitals) = canadian_capitals, mexican_capitals, us_capitals
给定三个与变量相关的词典,canadian_capitals,mexican_capitals和us_capitals,将省或州映射到各自的大写字母,创建一个新词典,将这三个词典组合在一起,并将其与变量nafta_capitals相关联。
答案 0 :(得分:1)
您可能需要使用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']