09-21-2020, 02:58 PM
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 listin one line of Python.
Example: Say, you want to have the list indices as keys and the list elements as values.
Solution: There are multiple ways to accomplish this task. Let’s learn the most Pythonic one next:
The one-liner first creates an iterable of tuples from the list using the function. The constructorthan transforms this iterable of tuples to mappings. The tuplevalue becomes the new . The tuple value becomes the new .
Try it yourself in our interactive code shell:
https://trinket.io/embed/python/273d008079
Exercise: Explore the 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.
How do you accomplish this?
Solution: Use dictionary comprehension to replace the loop construct with a single line of Python.
Dictionary Comprehension is a concise and memory-efficient way to createand 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 printa 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 contains the function . This will ‘pretty print’ your dictionary. It sorts the keys alphabetically and printseach key-value pair on a newline.
Printingthe 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 iterateover a dictionary in Python in one line?
Example: Say, you want to go over each pair of a dictionary like this:
But you want to do it in a single line of Python code! How?
Solution: Use the method to obtain the iterable. Then, use a single-line for loop to iterate over it.
The output is the same while the code is much more concise. The method of a dictionary object creates an iterable of tuple pairs from the dictionary.
Python Update Dictionary in One Line
Challenge: Given a dictionary and a pair. The 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 to create a new mapping from to in the dictionary. There are two cases:
Here’s the code:
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:
Now, you may want to write this in a single line of code. You can do it the naive way:
An better alternative is the dictionary.setdefault() method:
— If is in the dictionary, return its value. If not, insert with a value of and return . defaults to .
You can simply ignore the return value to update a key in a dictionary if it isn’t already present.
The only inserts the key 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!
The post Python One Line Dictionary first appeared on Finxter.
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 listin one line of Python.
Example: Say, you want to have the list indices as keys and the list elements as values.
Code:
# 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:
Code:
# 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
Code:
dict(enumerate(a))Code:
(index, element)Code:
aCode:
enumerateCode:
dict()Code:
(key, value)Code:
indexCode:
keyCode:
elementCode:
valueTry it yourself in our interactive code shell:
https://trinket.io/embed/python/273d008079
Exercise: Explore the
Code:
enumerate()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.
Code:
a = ['Alice', 'Liz', 'Bob'] data = {}
for item in a: data[item] = itemHow do you accomplish this?
Solution: Use dictionary comprehension to replace the
Code:
forCode:
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 createand 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 printa 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
Code:
pprintCode:
pprintCode:
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'} '''Printingthe 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 iterateover a dictionary in Python in one line?
Example: Say, you want to go over each
Code:
(key, value)Code:
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
Code:
dict.items()Code:
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
Code:
items()Code:
(key, value)Python Update Dictionary in One Line
Challenge: Given a dictionary and a
Code:
(key, value)Code:
keySolution: Use the square bracket notation
Code:
dict[key] = valueCode:
keyCode:
value- The already existed before and was associated to the oldCode:
key. In this case, the newCode:value_oldoverwrites the oldCode:valueafter updating the dictionary.Code:value_old
- The didn’t exist before in the dictionary. In this case, it is created for the first time and associated toCode:
key.Code:value
Here’s the code:
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 oldChallenge 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:
Code:
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 oldNow, you may want to write this in a single line of code. You can do it the naive way:
Code:
if 'Alice' not in age: age['Alice'] = 20An better alternative is the dictionary.setdefault() method:
Code:
setdefault(key[, default])Code:
keyCode:
keyCode:
defaultCode:
defaultCode:
defaultCode:
NoneYou can simply ignore the return value to update a key in a dictionary if it isn’t already present.
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.setdefault('Alice', 20) print(f"Alice is {age['Alice']} years old")
# Alice is 19 years oldThe
Code:
age.setdefault('Alice', 20)Code:
'Alice'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!
The post Python One Line Dictionary first appeared on Finxter.

