将字符串映射到一组字符串的Python字典?
我希望能够制作一个以字符串作为键、以字符串集作为值的 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 用户(或者我是这么认为的,直到我遇到这个问题。)
I would like to be able to make a Python dictionary with strings as keys and sets of strings as the values. E.g.: { "crackers" : ["crunchy", "salty"] }
It must be a set, not a list.
However, when I try the following:
word_dict = dict()
word_dict["foo"] = set()
word_dict["foo"] = word_dict["foo"].add("baz")
word_dict["foo"] = word_dict["foo"].add("bang")
I get:
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'
If I do this:
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
I get:
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
Any tips on how to coerce Python into doing what I'd like? I'm an intermediate Python user (or so I thought, until I ran into this problem.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
set.add()
不会返回新的set
,它会修改调用它的set
。以这种方式使用它:另外,如果您使用
for
循环来迭代字典,那么您正在迭代键:或者您可以迭代
word_dict.items()
或word_dict.iteritems()
:set.add()
does not return a newset
, it modifies theset
it is called on. Use it this way:Also, if you use a
for
loop to iterate over a dict, you are iterating over the keys:Alternatively you could iterate over
word_dict.items()
orword_dict.iteritems()
:当您说
word_dict["foo"].add("baz")
时,您正在将 'baz' 添加到 word_dict["foo"] 集合中。该函数返回
None
——更新集合是一个副作用。因此最终将
word_dict["foo"]
设置为None
。只要
word_dict["foo"].add("baz")
就是正确的。在第二种情况下,当您说
遇到错误时,因为正确的语法是
仅循环
word_dict
中的键。在这种情况下,你想要的是。
When you say
word_dict["foo"].add("baz")
, you are adding 'baz' to the set word_dict["foo"].The function returns
None
-- updating the set is a side-effect. Soultimately sets
word_dict["foo"]
toNone
.Just
word_dict["foo"].add("baz")
would be correct.In the second scenario, when you say
you run into an error because the correct syntax is
to loop over just the keys in
word_dict
. In this situation, you wantinstead.
尝试:
看起来标准字典迭代器仅返回
key
而不是元组。证明:
Try:
It looks like standard dictionary iterator returns only
key
but not tuple.Proof:
问题是这样的:
当您调用
word_dict["foo"].add("baz")
时,您正在改变word_dict["foo"]
引用的集合到,并且该操作返回None
。因此,从右向左阅读您的语句,您将“baz”添加到word_dict["foo"]
引用的集合中,然后设置该操作的结果(即无
)到word_dict[“foo”]
。因此,要使其按预期工作,只需从语句中删除
word_dict["foo"] =
即可。默认情况下,字典会对其键进行迭代,因此您尝试执行以下操作时会出现 ValueError:
这里发生的情况是,对 word_dict 进行迭代仅返回一个键(例如“foo”),然后您尝试将其解压到变量中
键
&值
。解压“foo”会得到“f”、“o”和& “o”,这是一个太多的值,无法容纳两个变量,因此出现了 ValueError。正如其他人所说,您想要的是迭代字典的键值对,如下所示:
The problem is this:
When you call
word_dict["foo"].add("baz")
, you're mutating the set thatword_dict["foo"]
refers to, and that operation returnsNone
. So reading your statement right to left, you're adding "baz" to the set refered to byword_dict["foo"]
, and then setting the result of that operation (that is,None
) toword_dict["foo"]
.So, to make this work as you expect, just remove
word_dict["foo"] =
from your statement.Dictionaries iterate on their keys by default, hence the ValueError you try this:
What's happening here is that iterating on word_dict is returning a key only (say, "foo"), which you're then trying to unpack into the variables
key
&value
. Unpacking "foo" gives you "f", "o", & "o", which is one value too many to fit into two variables, and hence your ValueError.As others have stated, what you want is to iterate on the dictionary's key-value pairs, like so: