Merging two dicts in Python 3.5+ with a single expression

# How to merge two dictionaries
# in Python 3.5+

>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}

>>> z = {**x, **y}

>>> z
{'c': 4, 'a': 1, 'b': 3}

# In Python 2.x you could
# use this:
>>> z = dict(x, **y)
>>> z
{'a': 1, 'c': 4, 'b': 3}

# In these examples, Python merges dictionary keys
# in the order listed in the expression, overwriting 
# duplicates from left to right.s        
Lucky. um

Data Engineer at Capgemini | Specializing in Python | Pandas | Pyspark | GCP | BigQuery | FastAPI | CICD pipelines | Big data | Databricks | SQL | Microservices | ETL | EDA | Docker | Git

2 年

Compress function will be used

回复

要查看或添加评论,请登录

Harshit Jain的更多文章

  • positional only & keyword only arguments

    positional only & keyword only arguments

    # with using "/" you can represent parameters before it as positional argments and # with using "*" you can…

  • Build your own iterator

    Build your own iterator

    # Define your own iteraotr by using __iter__ & __next__ functions. class OddNumbers: def __iter__(self):…

  • "sep" & "end" parameter in print()

    "sep" & "end" parameter in print()

    #Their is one more cool way you can use to represent your print() function outputs. Default is to separate them with a…

  • Packing & Unpacking in python

    Packing & Unpacking in python

    # we can unpack iterables to variables in a single assignment using automatic unpacking. Below is an example of…

  • __init__() & __new__() in python

    __init__() & __new__() in python

    # __init__() behaves like a constructor and invoked automatically at the time of object declaration along with…

  • Python 3.5+ type annotations

    Python 3.5+ type annotations

    # Python 3.5+ supports 'type annotations' that can b # used with tools like Mypy to write statically typed Python: def…

  • Peeking Behind The Bytecode Curtain

    Peeking Behind The Bytecode Curtain

    # You can use Python's built-in "dis # module to disassemble functions and # inspect their CPython VM bytecode: >>>…

  • contextlib.suppress

    contextlib.suppress

    # In Python 3.4+ you can use # contextlib.

  • Python list slice syntax fun

    Python list slice syntax fun

    # Python's list slice syntax can be used without indices # for a few fun and useful things: # You can clear all…

  • When To Use __repr__ vs __str__?

    When To Use __repr__ vs __str__?

    # When To Use __repr__ vs __str__ # Emulate what the std lib does: >>> import datetime >>> today = datetime.date.

社区洞察

其他会员也浏览了