将集合转换为冻结集合作为字典的值
我有一个字典,它是作为对象初始化的一部分而构建的。我知道它在对象的生命周期内不会改变。字典将键映射到集合。我想将所有值从 set
转换为 frozenset
,以确保它们不会更改。目前我是这样做的:
for key in self.my_dict.iterkeys():
self.my_dict[key] = frozenset(self.my_dict[key])
有没有更简单的方法来实现这一目标?我无法立即构建frozenset
,因为在构建完整的字典之前,我不知道每个集合中有多少项目。
I have dictionary that is built as part of the initialization of my object. I know that it will not change during the lifetime of the object. The dictionary maps keys to sets. I want to convert all the values from set
s to frozenset
s, to make sure they do not get changed. Currently I do that like this:
for key in self.my_dict.iterkeys():
self.my_dict[key] = frozenset(self.my_dict[key])
Is there a simpler way to achieve this? I cannot build frozenset
right away, because I do not how much items will be in each set until i have built the complete dictionary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
例如,
您可以就地进行转换,如
结果所示
Given, for instance,
You can do the conversion in place as
With the result
如果您必须就地执行此操作,可能这是最简单的方法(几乎与您发布的相同):
这是构建临时字典的变体:
If you have to do it in-place, probably this is the simplest way (almost the same as you posted):
This a variant which builds a temporary dict:
在 Python 3 中,您可以使用字典理解:
不过,在 Python 2 中,我不知道有什么更短的东西——这至少感觉不那么“冗余”:
In Python 3, you could use a dictionary comprehension:
In Python 2, though, I don't know that there's anything shorter -- this at least feels less "redundant":