python - 在 python 中是否有类似 updated 的东西来更新 sorted 是要排序的?

标签 python dictionary

在 python 中,如果我执行以下操作:

>>> list = [ 3, 2, 1]
>>> sorted_list = k.sort()

那么sorted_listNone并且list是排序的:

>>> sorted_list = k.sort()
>>> print list, sorted_list
[1, 2, 3] None

但是,如果我执行以下操作:

>>> list = [ 3, 2, 1]
>>> sorted_list = sorted(list)

然后 list 保持未排序并且 sorted_list 包含已排序列表的副本:

>>> print list, sorted_list
[3, 2, 1] [1, 2, 3]

我想知道字典的 update 函数是否有等价物。

这样我就可以做这样的事情:

def foo(a, b, extra={}):
    bar = { 'first': a, 'second': b }
    special_function(**updated(bar, extra))
    normal_function(**bar)

而不是必须做这样的事情:

def foo(a, b, extra={}):
    bar = { 'first': a, 'second': b }
    special_bar = bar.copy()
    special_bar.update(extra) # [1]
    special_function(**special_bar)
    normal_function(**bar)

[1] 是的,我知道我可以简单地将这两行替换为 extra.update(bar) 但假设我想保留 extra稍后在函数中使用。

我意识到我可以自己实现这个:

def updated(old_dict, extra={}):
    new_dict = old_dict.copy()
    new_dict.update(extra)
    return new_dict

或以下高度不可读的就地语句:

    special_function(**(dict(bar.items()+extra.items())))

但我希望内置了一些我已经可以使用的东西。

最佳答案

你可以简单地使用内置的dict():

updated_dict = dict(old_dict, **extra_dict)

关于python - 在 python 中是否有类似 updated 的东西来更新 sorted 是要排序的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9486089/

相关文章:

python - 终端中 Python 的 virtualenv 出错

python - 为 Python 函数的字典列表指定参数类型

python - 获取嵌套字典值的安全方法

python - 使用嵌套字典作为数据帧的查找表时返回错误

python - 检查索引对象值类型

python - 在 Python 中保持字典中的值相同

python - 如何从列表 Python 创建类实例

python - 按数组python中的字典值排序

python - 如何选择列表框中的多个项目?

python - 检查字符串是否包含列表项