2016-11-30 77 views
1

假设我有一个列表字典,并且每个列表元素都是一个集合。在字典中引用列表中的一个集合的值

例子:

from collections import defaultdict 

shoppingList = defaultdict(list) 

shoppingList["produce"].append({"carrot",4}) 
shoppingList["produce"].append({"lettuce",2}) 
shoppingList["produce"].append({"tomato",2}) 
shoppingList["dairy"].append({"eggs",12}) 

我怎么会参考个人设定的值?例如,如果我想专门打印出我需要多少个鸡蛋(在{“eggs”,12}中将其存储为值“12”),而不知道列表中的哪个位置具有关键“鸡蛋“ 被储存了?或者,如果我想编辑蛋的数量?

+0

..然后你使用了错误的数据结构。考虑使用如下的元组:(“胡萝卜”,4)。记住元组是不可变的,如果你试图更新它,你将不得不创建一个新的元组。或者直接使用2元素列表。 – SuperSaiyan

回答

1

,而不使用包含集合,则可以只使用嵌套词典这将使访问和更新琐碎名单词典:

from collections import defaultdict 

shoppingList = defaultdict(dict) 

shoppingList["produce"]["carrot"] = 4 
shoppingList["produce"]["lettuce"] = 2 
shoppingList["produce"]["tomato"] = 2 
shoppingList["dairy"]["eggs"] = 12 

print(shoppingList["dairy"]["eggs"]) # 12 

shoppingList["dairy"]["eggs"] += 2 
print(shoppingList["dairy"]["eggs"]) # 14 
+0

非常感谢!这使事情变得更容易。 – Lorraine