将字符串映射到一组字符串的Python字典?

发布于 2024-08-22 08:10:05 字数 1326 浏览 2 评论 0原文

我希望能够制作一个以字符串作为键、以字符串集作为值的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

我乃一代侩神 2024-08-29 08:10:05

set.add() 不会返回新的set,它会修改调用它的set。以这种方式使用它:

word_dict = dict()
word_dict["foo"] = set()
word_dict["foo"].add("baz")                                    
word_dict["foo"].add("bang")

另外,如果您使用 for 循环来迭代字典,那么您正在迭代键:

for key in word_dict:
   print key, word_dict[key]

或者您可以迭代 word_dict.items()word_dict.iteritems()

for key, value in word_dict.items():
   print key, value

set.add() does not return a new set, it modifies the set it is called on. Use it this way:

word_dict = dict()
word_dict["foo"] = set()
word_dict["foo"].add("baz")                                    
word_dict["foo"].add("bang")

Also, if you use a for loop to iterate over a dict, you are iterating over the keys:

for key in word_dict:
   print key, word_dict[key]

Alternatively you could iterate over word_dict.items() or word_dict.iteritems():

for key, value in word_dict.items():
   print key, value
温柔嚣张 2024-08-29 08:10:05
from collections import defaultdict

word_dict = defaultdict(set)
word_dict['banana'].add('yellow')
word_dict['banana'].add('brown')
word_dict['apple'].add('red')
word_dict['apple'].add('green')
for key,values in word_dict.iteritems():
    print "%s: %s" % (key, values)
from collections import defaultdict

word_dict = defaultdict(set)
word_dict['banana'].add('yellow')
word_dict['banana'].add('brown')
word_dict['apple'].add('red')
word_dict['apple'].add('green')
for key,values in word_dict.iteritems():
    print "%s: %s" % (key, values)
悲念泪 2024-08-29 08:10:05

当您说 word_dict["foo"].add("baz") 时,您正在将 'baz' 添加到 word_dict["foo"] 集合中。

该函数返回None——更新集合是一个副作用。因此

word_dict["foo"] = word_dict["foo"].add("baz") 

最终将 word_dict["foo"] 设置为 None

只要 word_dict["foo"].add("baz") 就是正确的。

在第二种情况下,当您说

for key, value in word_dict:                                                       

遇到错误时,因为正确的语法是

for key in word_dict: 

仅循环 word_dict 中的键。在这种情况下,你想要的

for key,value in word_dict.iteritems(): 

是。

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. So

word_dict["foo"] = word_dict["foo"].add("baz") 

ultimately sets word_dict["foo"] to None.

Just word_dict["foo"].add("baz") would be correct.

In the second scenario, when you say

for key, value in word_dict:                                                       

you run into an error because the correct syntax is

for key in word_dict: 

to loop over just the keys in word_dict. In this situation, you want

for key,value in word_dict.iteritems(): 

instead.

念﹏祤嫣 2024-08-29 08:10:05

尝试:

word_dict = dict()
myset = set()
myset.add("bar")
word_dict["foo"] = myset
myset.add("bang")
word_dict["foo"] = myset

for key in word_dict:                                                       
    print key, word_dict[key]

看起来标准字典迭代器仅返回 key 而不是元组。

证明:

>>> d = { 'test': 1 }
>>> for k, v in d: print k, v
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>> for k in d: print d[k]
... 
1

Try:

word_dict = dict()
myset = set()
myset.add("bar")
word_dict["foo"] = myset
myset.add("bang")
word_dict["foo"] = myset

for key in word_dict:                                                       
    print key, word_dict[key]

It looks like standard dictionary iterator returns only key but not tuple.

Proof:

>>> d = { 'test': 1 }
>>> for k, v in d: print k, v
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>> for k in d: print d[k]
... 
1
你曾走过我的故事 2024-08-29 08:10:05

问题是这样的:

word_dict["foo"] = word_dict["foo"].add("baz")   

当您调用 word_dict["foo"].add("baz") 时,您正在改变 word_dict["foo"] 引用的集合到,并且该操作返回None。因此,从右向左阅读您的语句,您将“baz”添加到 word_dict["foo"] 引用的集合中,然后设置该操作的结果(即 )到word_dict[“foo”]

因此,要使其按预期工作,只需从语句中删除 word_dict["foo"] = 即可。

默认情况下,字典会对其键进行迭代,因此您尝试执行以下操作时会出现 ValueError:

for key, value in word_dict: 

这里发生的情况是,对 word_dict 进行迭代仅返回一个键(例如“foo”),然后您尝试将其解压到变量中 & 。解压“foo”会得到“f”、“o”和& “o”,这是一个太多的值,无法容纳两个变量,因此出现了 ValueError。

正如其他人所说,您想要的是迭代字典的键值对,如下所示:

for key, value in word_dict.iteritems (): 

The problem is this:

word_dict["foo"] = word_dict["foo"].add("baz")   

When you call word_dict["foo"].add("baz"), you're mutating the set that word_dict["foo"] refers to, and that operation returns None. So reading your statement right to left, you're adding "baz" to the set refered to by word_dict["foo"], and then setting the result of that operation (that is, None) to word_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:

for key, value in word_dict: 

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:

for key, value in word_dict.iteritems (): 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文