将集合转换为冻结集合作为字典的值

发布于 2024-09-05 18:24:15 字数 330 浏览 3 评论 0原文

我有一个字典,它是作为对象初始化的一部分而构建的。我知道它在对象的生命周期内不会改变。字典将键映射到集合。我想将所有值从 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 sets to frozensets, 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 技术交流群。

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

发布评论

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

评论(3

怼怹恏 2024-09-12 18:24:15

例如,

>>> d = {'a': set([1, 2]), 'b': set([3, 4])}
>>> d
{'a': set([1, 2]), 'b': set([3, 4])}

您可以就地进行转换,如

>>> d.update((k, frozenset(v)) for k, v in d.iteritems())

结果所示

>>> d
{'a': frozenset([1, 2]), 'b': frozenset([3, 4])}

Given, for instance,

>>> d = {'a': set([1, 2]), 'b': set([3, 4])}
>>> d
{'a': set([1, 2]), 'b': set([3, 4])}

You can do the conversion in place as

>>> d.update((k, frozenset(v)) for k, v in d.iteritems())

With the result

>>> d
{'a': frozenset([1, 2]), 'b': frozenset([3, 4])}
对风讲故事 2024-09-12 18:24:15

如果您必须就地执行此操作,可能这是最简单的方法(几乎与您发布的相同):

for key, value in self.my_dict.iteritems():
    self.my_dict[key] = frozenset(value)

这是构建临时字典的变体:

self.my_dict = dict(((key, frozenset(value)) \
                    for key, value in self.my_dict.iteritems()))

If you have to do it in-place, probably this is the simplest way (almost the same as you posted):

for key, value in self.my_dict.iteritems():
    self.my_dict[key] = frozenset(value)

This a variant which builds a temporary dict:

self.my_dict = dict(((key, frozenset(value)) \
                    for key, value in self.my_dict.iteritems()))
云之铃。 2024-09-12 18:24:15

在 Python 3 中,您可以使用字典理解:

d = {k: frozenset(v) for k, v in d.items()}

不过,在 Python 2 中,我不知道有什么更短的东西——这至少感觉不那么“冗余”:

for k,v in d.iteritems():
    d[k] = frozenset(v)

In Python 3, you could use a dictionary comprehension:

d = {k: frozenset(v) for k, v in d.items()}

In Python 2, though, I don't know that there's anything shorter -- this at least feels less "redundant":

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