Daniel Roy Greenfeld

Daniel Roy Greenfeld

About | Articles | Open Source | Books | Tags | Search

TIL: Python Dictonary Merge Operator

Did you know there's a merge operator for Python dictionaries? I didn't until today!

The function way

Until today I did this:

# Make first dict
num_map = {
    'one': '1', 'two': '2', 'three': '3', 'four': '4',
    'five': '5', 'six': '6', 'seven': '7', 'eight': '8',
    'nine': '9'
}
# Add second dict
num_map.update({str(x):str(x) for x in range(1,10)})
print(num_map)

The operator way

Now thanks to Audrey Roy Greenfeld now I know I can do this:

# Make first dict while adding second dict
num_map = {
    'one': '1', 'two': '2', 'three': '3', 'four': '4',
    'five': '5', 'six': '6', 'seven': '7', 'eight': '8',
    'nine': '9'
} | {str(x):str(x) for x in range(1,10)}
print(num_map)
Today I Learned

Tags: TIL python

← Back to all articles

Search