Is it possible to copy and update a python dictionary in a single-chain expression?

Consider the following:

x = {1:2}
y = x.copy() # returns a new dictionary
y = x.copy().update({2:3}) # returns None
y = x.copy()[2] = 3 # invalid syntax

Given that none of the above work exists, is there a way to associate a command with Dict.copy()to copy and update the dictionary in one command?

+4
source share
4 answers

Yes, you can use the dict()function to create a copy and add keyword arguments; use **{...}to add arbitrary keys that are not Python identifiers:

y = dict(x, **{2: 3})

, Python ( , ), dict():

y = dict(x, foo_bar='spam_eggs')

:

y = dict(x, foo='spam', bar='eggs', **{2: 3, 42: 81})

:

>>> x = {1: 2}
>>> dict(x, **{2: 3})
{1: 2, 2: 3}
>>> dict(x, foo_bar='spam_eggs')
{1: 2, 'foo_bar': 'spam_eggs'}
>>> dict(x, foo='spam', bar='eggs', **{2: 3, 42: 81})
{1: 2, 2: 3, 'foo': 'spam', 'bar': 'eggs', 42: 81}
>>> x  # not changed, copies were made
{1: 2}
+8

Python 2 :

y = dict(x.items()+{2:3}.items())

y = dict(x.items()+[(2, 3)])
+3

dict:

y = {
    k:v
    for dct in ( x, {2:3} )
    for k,v in dct.items()
}
+3

, "x.copy()", , , . "x.copy()" "x".

x = {1:2}
y = x.copy() # first new copy, saved as "y"
y = x.copy().update({2:3}) # a second new copy, which is not saved because the 
                           # result of the update() method (which is None) is saved
y = x.copy()[2] = 3 # A third new copy is created, but it the same as the
                    # original x, and has no key value of "2"

, -, , ,

y = x.copy(); y.update({2:3})
0

Source: https://habr.com/ru/post/1614813/


All Articles