我想创建一个Python字典,以字符串为键,以字符串集合为值。例如:
{ "crackers" : ["crunchy", "salty"] }
必须是一个集合,而不是列表。但是,当我尝试以下操作时: 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用户(或者这样认为,直到遇到这个问题)。
dict.iteritems()
重命名为dict.items()
。 - zvi