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

编程入门 行业动态 更新时间:2024-10-28 08:20:33
本文介绍了将字符串映射到一组字符串的Python字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用一个Python字典作为键和字符串作为值的字符串。例如: {crackers:[crunchy,salty]} 它必须是一个集合,而不是列表。

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")

我得到:

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用户(或者我以为,直到我遇到这个问题。)

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

推荐答案

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

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")

另外,如果您使用循环的循环使用dict,那么您将迭代键:

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]

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

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

更多推荐

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

本文发布于:2023-10-23 03:31:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519625.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字典   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!