10 Python One-Liners for Dictionaries

Shen Ge
Published in
4 min readDec 24, 2021

Photo by Sandy Millar on Unsplash

Background on Dictionaries

Previously, I wrote an article of ten one-liners for Python lists. Another important built-in data type in Python is dictionaries. Whereas lists are ordered collections of objects, dictionaries are unordered collections. Instead of positional offsets (indices) as in lists, dictionary elements are stored and fetched by keys. Dictionaries are extremely useful where item names are more meaningful than item positions.

To declare a dictionary is simple. Instead of using brackets [] as in lists use curly braces {} . Example: D = {} will create an empty dictionary called D. To create a dictionary with some items, simply write a key and a value separated by a colon (:). Example: D = {'spam': 2, 'ham': 1, 'eggs': 3}

Another way to make dictionaries is to use the dict keyword argument in two variations:

# dict keyword argument form
>>> dict(spam=2,ham=1,eggs=3)
{'spam': 2, 'ham': 1, 'eggs': 3}
# dict key value tuples form
>>> dict([('spam',2),('ham',1),('eggs',3)])
{'spam': 2, 'ham': 1, 'eggs': 3}

Note that either the key or value can be anything and they don’t even to have to be all the same type. This is perfectly acceptable where the keys are tuples, strings and integer whereas the values are strings, integer, and list of floats: A={(2,3): 'prime1', (5,7): 'prime2', 'numprimes': 4, 9: [9.0,3.0,1.7]} .

Let us get started with 10 common Python one-liners for dictionaries.

1. Change entry

>>> D['ham'] = ['grill, 'bake', 'fry']
>>> D
{'eggs': 3, 'spam': 2, 'ham': ['grill', 'bake', 'fry']

2. Delete entry

>>> del D['eggs']
>>> D
{'spam': 2, 'ham': ['grill', 'bake', 'fry']

3. Add new entry.

Unlike lists, assigning an existing index in a dictionary changes its associated value. Whenever you assign a new dictionary key, you create a new entry in the dictionary. For instance, here we add a new key 'brunch' . This does not work for lists because Python considers an offset (index) beyond the end of list out of bounds and raises an error. For lists, you need to use append or extend method.

Shen Ge
Writer for

Aerospace engineer who enjoys Python, math, physics, space and poetry. Become a member and read all my work: https://medium.com/@shenge86/membership

Recommended from Medium


See more recommendations