在Python迭代期间添加新键或追加到字典中旧键的最有效方法?

发布于 2024-08-08 01:45:01 字数 811 浏览 3 评论 0原文

这是在不同来源的字典中编译数据时的常见情况:

假设您有一个存储事物列表的字典,例如我喜欢的事物:

likes = {
    'colors': ['blue','red','purple'],
    'foods': ['apples', 'oranges']
}

以及第二个字典,其中包含一些相关值:

favorites = {
    'colors':'yellow',
    'desserts':'ice cream'
}

然后您想要迭代“收藏夹” “对象,并使用“喜欢”字典中的适当键将该对象中的项目附加到列表中,或者向其添加一个新键,其值是包含“收藏夹”中的值的列表。

有几种方法可以做到这一点:

for key in favorites:
    if key in likes:
        likes[key].append(favorites[key])
    else:
        likes[key] = list(favorites[key])

for key in favorites:
    try:
        likes[key].append(favorites[key])
    except KeyError:
        likes[key] = list(favorites[key])

还有更多...

我通常使用第一种语法,因为它感觉更Pythonic,但如果有其他更好的方法,我很想知道它们是什么。谢谢!

Here's a common situation when compiling data in dictionaries from different sources:

Say you have a dictionary that stores lists of things, such as things I like:

likes = {
    'colors': ['blue','red','purple'],
    'foods': ['apples', 'oranges']
}

and a second dictionary with some related values in it:

favorites = {
    'colors':'yellow',
    'desserts':'ice cream'
}

You then want to iterate over the "favorites" object and either append the items in that object to the list with the appropriate key in the "likes" dictionary or add a new key to it with the value being a list containing the value in "favorites".

There are several ways to do this:

for key in favorites:
    if key in likes:
        likes[key].append(favorites[key])
    else:
        likes[key] = list(favorites[key])

or

for key in favorites:
    try:
        likes[key].append(favorites[key])
    except KeyError:
        likes[key] = list(favorites[key])

And many more as well...

I generally use the first syntax because it feels more pythonic, but if there are other, better ways, I'd love to know what they are. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(5

深爱成瘾 2024-08-15 01:45:01

使用 collections.defaultdict,其中默认值是一个新的 list 实例。

>>> import collections
>>> mydict = collections.defaultdict(list)

通过这种方式,调用 .append(...) 将始终成功,因为如果键不存在,append 将在新的空列表上调用。

您可以使用之前生成的列表实例化 defaultdict,以防您从其他来源获取字典 likes,如下所示:

>>> mydict = collections.defaultdict(list, likes)

请注意,使用 list因为 defaultdictdefault_factory 属性也在 文档

Use collections.defaultdict, where the default value is a new list instance.

>>> import collections
>>> mydict = collections.defaultdict(list)

In this way calling .append(...) will always succeed, because in case of a non-existing key append will be called on a fresh empty list.

You can instantiate the defaultdict with a previously generated list, in case you get the dict likes from another source, like so:

>>> mydict = collections.defaultdict(list, likes)

Note that using list as the default_factory attribute of a defaultdict is also discussed as an example in the documentation.

寄离 2024-08-15 01:45:01

使用 collections.defaultdict:

import collections

likes = collections.defaultdict(list)

for key, value in favorites.items():
    likes[key].append(value)

defaultdict 采用单个参数,即一个用于根据需要为未知键创建值的工厂。 list 就是这样一个函数,它创建空列表。

迭代 .items() 将使您免于使用键来获取值。

Use collections.defaultdict:

import collections

likes = collections.defaultdict(list)

for key, value in favorites.items():
    likes[key].append(value)

defaultdict takes a single argument, a factory for creating values for unknown keys on demand. list is a such a function, it creates empty lists.

And iterating over .items() will save you from using the key to get the value.

过潦 2024-08-15 01:45:01

除了 defaultdict 之外,常规 dict 还提供了一种可能性(可能看起来有点奇怪): dict.setdefault(k[, d])

for key, val in favorites.iteritems():
    likes.setdefault(key, []).append(val)

谢谢您的 +20 代表 - 我从 1989 年开始30 秒后到 2009 年。让我们记住,欧洲柏林墙倒塌已有 20 年了。

Except defaultdict, the regular dict offers one possibility (that might look a bit strange): dict.setdefault(k[, d]):

for key, val in favorites.iteritems():
    likes.setdefault(key, []).append(val)

Thank you for the +20 in rep -- I went from 1989 to 2009 in 30 seconds. Let's remember it is 20 years since the Wall fell in Europe..

多情出卖 2024-08-15 01:45:01
>>> from collections import defaultdict
>>> d = defaultdict(list, likes)
>>> d
defaultdict(<class 'list'>, {'colors': ['blue', 'red', 'purple'], 'foods': ['apples', 'oranges']})
>>> for i, j in favorites.items():
    d[i].append(j)

>>> d
defaultdict(<class 'list'>, {'desserts': ['ice cream'], 'colors': ['blue', 'red', 'purple', 'yellow'], 'foods': ['apples', 'oranges']})
>>> from collections import defaultdict
>>> d = defaultdict(list, likes)
>>> d
defaultdict(<class 'list'>, {'colors': ['blue', 'red', 'purple'], 'foods': ['apples', 'oranges']})
>>> for i, j in favorites.items():
    d[i].append(j)

>>> d
defaultdict(<class 'list'>, {'desserts': ['ice cream'], 'colors': ['blue', 'red', 'purple', 'yellow'], 'foods': ['apples', 'oranges']})
怪我入戏太深 2024-08-15 01:45:01

所有答案都是 defaultdict,但我不确定这是最好的方法。向需要字典的代码提供 defaultdict 可能会很糟糕。 (请参阅:如何使 defaultdict 对于意外情况安全客户?)我个人对这个问题感到左右为难。 (我实际上发现这个问题正在寻找“哪个更好,dict.get()”或“defaultdict”的答案)另一个线程中的某人说你不如果您不希望一直出现这种行为,则需要一个 defaultdict,这可能是正确的。也许为了方便而使用 defaultdict 是错误的方法。我认为这里有两个需求被混为一谈:

“我想要一个默认值为空列表的字典。”其中 defaultdict(list) 是正确的解决方案。

“如果存在,我想将其追加到该键的列表中,如果不存在,则创建一个列表。”答案是 my_dict.get('foo', [])append()

你们觉得怎么样?

All of the answers are defaultdict, but I'm not sure that's the best way to go about it. Giving out defaultdict to code that expects a dict can be bad. (See: How do I make a defaultdict safe for unexpecting clients? ) I'm personally torn on the matter. (I actually found this question looking for an answer to "which is better, dict.get() or defaultdict") Someone in the other thread said that you don't want a defaultdict if you don't want this behavior all the time, and that might be true. Maybe using defaultdict for the convenience is the wrong way to go about it. I think there are two needs being conflated here:

"I want a dict whose default values are empty lists." to which defaultdict(list) is the correct solution.

and

"I want to append to the list at this key if it exists and create a list if it does not exist." to which my_dict.get('foo', []) with append() is the answer.

What do you guys think?

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