【问题标题】:How to use spread operator in Python [duplicate]如何在 Python 中使用扩展运算符 [重复]
【发布时间】:2020-03-10 11:40:58
【问题描述】:

我正在使用 Python 2.7,我想使用一些东西作为 Javascript 扩展运算符。

我有以下代码:

def some_function():
  return {
        'a': "test",
        'b': 1,
        'c': 2
    } 

mapper = some_function()

test = mapper.update({'a': "Updated"})

print(test)

我想要的结果是:

{
   'a': "Updated",
   'b': 1,
   'c': 2
}

但我得到的是None

有什么想法吗?

【问题讨论】:

  • 测试映射到mapper.update的返回。尝试打印(映射器)而不是
  • mapper 现已更新,请参阅print(mapper)。你是说你想让test 更新a 而不更改mapper
  • @deceze 是的,这就是我想要的。
  • Python 中的一般设计规则是:如果一个函数对一个已经存在的对象进行操作,则该对象将不会被返回。这称为就地操作。
  • 他们 python 文档是你的朋友docs.python.org/2/library/stdtypes.html#dict.update 它告诉Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None. 所以它会更新你给它的对象,它不会返回更新。

标签: python python-2.7


【解决方案1】:

dict.update 发生在原地,因此返回 None,因此不要将结果分配给变量。

mapper = some_function()
mapper.update({'a': "Updated"})
print(mapper)
#{'a': "Updated", 'b': 1, 'c': 2}

或者,如果您想保留 mapper 但分配更新后的值,您可以使用星号解包创建一个新的字典:

test = {**mapper, 'a': 'Updated'}

【讨论】:

    猜你喜欢
    • 2020-04-13
    • 2021-10-24
    • 2021-03-10
    • 1970-01-01
    • 2019-06-15
    • 2012-03-28
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多