我想能夠使用字符串作爲鍵和字符串作爲值來創建Python字典。例如:{ "crackers" : ["crunchy", "salty"] }
它必須是一個集合,而不是一個列表。將字符串映射到一組字符串的Python字典?
但是,當我嘗試以下方法:
word_dict = dict()
word_dict["foo"] = set()
word_dict["foo"] = word_dict["foo"].add("baz")
word_dict["foo"] = word_dict["foo"].add("bang")
我得到:
Traceback (most recent call last):
File "process_input.py", line 56, in <module>
test()
File "process_input.py", line 51, in test
word_dict["foo"] = word_dict["foo"].add("bang")
AttributeError: 'NoneType' object has no attribute 'add'
如果我這樣做:
word_dict = dict()
myset = set()
myset.add("bar")
word_dict["foo"] = myset
myset.add("bang")
word_dict["foo"] = myset
for key, value in word_dict:
print key,
print value
我得到:
Traceback (most recent call last):
File "process_input.py", line 61, in <module>
test()
File "process_input.py", line 58, in test
for key, value in word_dict:
ValueError: too many values to unpack
關於如何強制Python做我想做的任何提示?我是一箇中間的Python用戶(我這樣想着,直到我遇到了這個問題。)
謝謝。當然,呃。 – 2010-02-18 02:36:17