Skip to content

Instantly share code, notes, and snippets.

@nlpjoe
Last active January 31, 2018 08:10
Show Gist options
  • Select an option

  • Save nlpjoe/116da7bb1efd88c016cdea13b9b5aba3 to your computer and use it in GitHub Desktop.

Select an option

Save nlpjoe/116da7bb1efd88c016cdea13b9b5aba3 to your computer and use it in GitHub Desktop.
[merge two dicts] #python

Q

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{'a': 1, 'b': 10, 'c': 11}

如何合并字典且不改变x

A:

In Python 3.5 or greater, :

z = {**x, **y}

In Python 2, (or 3.4 or lower) write a function:

def merge_two_dicts(x, y):
    z = x.copy()   # start with x's keys and values
    z.update(y)    # modifies z with y's keys and values & returns None
    return z

z = merge_two_dicts(x, y)

python2

z = dict(x.items() + y.items())

python3

z = dict(list(x.items()) + list(y.items()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment