我是一个新手,正在学习 python 中的字典,并且花了一天的大部分时间来解决它,我将不胜感激!
我想创建一个字典字典:
data = [['dog', 'a'], ['mouse', 'a'], ['dog', 'b'], ['mouse', 'c'], ['dog', 'c']]
animals = ['dog', 'mouse']
我想这样做:
final = {'dog': {'a': 0, 'b': 0, 'c': 0}, 'mouse':{'a': 0, 'c': 0} }
到目前为止,我有这段代码,这显然是行不通的:
animal_dict = {}
for d in data:
animal_dict[d[0]] = {}
letter_dict = {}
for animal in animal_dict:
for d in data:
if d[0] == animal:
letter_dict[d[1]] = 0
animal_dict[animal] = letter_dict
print animal_dict
请注意,它在“鼠标”字典中添加了一个额外的键(“b”)。我知道我让它变得比它应该的更复杂!在此先感谢您对新手的帮助。