10 Python One-Liners for Dictionaries

Shen Ge
CodeX
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…

--

--

Shen Ge
CodeX

Engineer and console operator who helped America land back on the moon 2/22/2024. Enjoys code + poetry. Become a member: https://medium.com/@shenge86/membership