Python One Line Dictionary

Python’s dictionary data structure is one of the most powerful, most underutilized data structures in Python. Why? Because checking membership is more efficient for dictionaries than for lists, while accessing elements is easier for dictionaries than for sets.

In this tutorial, you’ll learn how to perform four common dictionary operations in one line of Python code. By studying these problems, you’ll not only learn how to use dictionaries in Python, but you’ll become a better coder overall. So, let’s dive into the first problem: creating a dictionary from a list in one line.

Python Create Dictionary From List in One Line

Challenge: Create a dictionary from a list in one line of Python.

Example: Say, you want to have the list indices as keys and the list elements as values.

# Given a list:
a = ['Alice', 'Liz', 'Bob']

# One-Line Statement Creating a Dict:
d = one-line-statement

print(d)
# {0: 'Alice', 1: 'Liz', 2: 'Bob'}

Solution: There are multiple ways to accomplish this task. Let’s learn the most Pythonic one next:

# Given a list:
a = ['Alice', 'Liz', 'Bob']

# One-Line Statement Creating a Dict:
d = dict(enumerate(a))

print(d)
# {0: 'Alice', 1: 'Liz', 2: 'Bob'}

The one-liner dict(enumerate(a)) first creates an iterable of (index, element) tuples from the list a using the enumerate function. The dict() constructor than transforms this iterable of tuples to (key, value) mappings. The index tuple value becomes the new key. The element tuple value becomes the new value.

Try it yourself in our interactive code shell:

Exercise: Explore the enumerate() function further by printing its output!

Python One Line For Loop to Create Dictionary

Challenge: How to create a dictionary from all elements in a list using a single-line for loop?

Example: Say, you want to replace the following four-liner code snippet with a Python one-liner.

a = ['Alice', 'Liz', 'Bob']

data = {}
for item in a:
    data[item] = item

How do you accomplish this?

Solution: Use dictionary comprehension to replace the for loop construct with a single line of Python.

a = ['Alice', 'Liz', 'Bob']

# One-Liner Dictionary For Loop
data = {item:item for item in a}

print(data)
# {'Alice': 'Alice', 'Liz': 'Liz', 'Bob': 'Bob'}

Dictionary Comprehension is a concise and memory-efficient way to create and initialize dictionaries in one line of Python code. It consists of two parts: expression and context. The expression defines how to map keys to values. The context loops over an iterable using a single-line for loop and defines which (key,value) pairs to include in the new dictionary.

You can learn about dictionary comprehension in my full video tutorial:

Related Article: Dictionary Comprehension — Complete Guide

Python Print Dictionary One Line

Challenge: How can you print a dictionary in a well-structured way using only a single line of Python code (without using multiple lines to create the output)?

Solution: Use the pretty print function!

The built-in module pprint contains the function pprint. This will ‘pretty print’ your dictionary. It sorts the keys alphabetically and prints each key-value pair on a newline.

from pprint import pprint
messy_dict = dict(z='Here is a really long key that spans a lot of text', a='here is another long key that is really too long', j='this is the final key in this dictionary')
 
pprint(messy_dict)
'''
{'a': 'here is another long key that is really too long',
'j': 'this is the final key in this dictionary',
'z': 'Here is a really long key that spans a lot of text'}
'''

Printing the dictionary this way, doesn’t change the dictionary in any way but makes it more readable on the Python shell!

Iterate Over Dictionary Python One Line

Challenge: How to iterate over a dictionary in Python in one line?

Example: Say, you want to go over each (key, value) pair of a dictionary like this:

age = {'Alice': 19, 'Bob': 23, 'Frank': 53}

# Iterate over dictionary (key, value) pairs
for name in age:
    key, value = name, age[name]
    print(key, value)

'''
OUTPUT:
Alice 19
Bob 23
Frank 53
'''

But you want to do it in a single line of Python code! How?

Solution: Use the dict.items() method to obtain the iterable. Then, use a single-line for loop to iterate over it.

age = {'Alice': 19, 'Bob': 23, 'Frank': 53}

# Iterate over dictionary (key, value) pairs
for k,v in age.items(): print(k,v)

'''
OUTPUT:
Alice 19
Bob 23
Frank 53
'''

The output is the same while the code is much more concise. The items() method of a dictionary object creates an iterable of (key, value) tuple pairs from the dictionary.

Python Update Dictionary in One Line

Challenge: Given a dictionary and a (key, value) pair. The key may or may not already exist in the dictionary. How to update the dictionary in one line of Python?

Solution: Use the square bracket notation dict[key] = value to create a new mapping from key to value in the dictionary. There are two cases:

  • The key already existed before and was associated to the old value_old. In this case, the new value overwrites the old value_old after updating the dictionary.
  • The key didn’t exist before in the dictionary. In this case, it is created for the first time and associated to value.

Here’s the code:

age = {'Alice': 19, 'Bob': 23, 'Frank': 53}

print(f"Alice is {age['Alice']} years old")
# Alice is 19 years old

# Alice's Birthday
age['Alice'] = 20

print(f"Alice is {age['Alice']} years old")
# Alice is 20 years old

Challenge 2: But what if you want to update only if the key didn’t exist before. In other words, you don’t want to overwrite an existing mapping?

Solution: In this case, you can use the check if key in dict to differentiate the two cases:

age = {'Alice': 19, 'Bob': 23, 'Frank': 53}

print(f"Alice is {age['Alice']} years old")
# Alice is 19 years old

# Alice's Birthday
if 'Alice' not in age:
    age['Alice'] = 20

print(f"Alice is {age['Alice']} years old")
# Alice is 19 years old

Now, you may want to write this in a single line of code. You can do it the naive way:

if 'Alice' not in age: age['Alice'] = 20

An better alternative is the dictionary.setdefault() method:

setdefault(key[, default]) — If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

You can simply ignore the return value to update a key in a dictionary if it isn’t already present.

age = {'Alice': 19, 'Bob': 23, 'Frank': 53}

print(f"Alice is {age['Alice']} years old")
# Alice is 19 years old

# Alice's Birthday
age.setdefault('Alice', 20)

print(f"Alice is {age['Alice']} years old")
# Alice is 19 years old

The age.setdefault('Alice', 20) only inserts the key 'Alice' if it isn’t already present (in which case it would associate the value 20 to it). But because it already exists, the command has no side effects and the new value does not overwrite the old one.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!