Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line Dictionary
1
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.

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))
first creates an iterable of
Code:
(index, element)
tuples from the list
Code:
a
using the
Code:
enumerate
function. The
Code:
dict()
constructorthan transforms this iterable of tuples to
Code:
(key, value)
mappings. The
Code:
index
tuplevalue becomes the new
Code:
key
. The
Code:
element
tuple value becomes the new
Code:
value
.

Try it yourself in our interactive code shell:

https://trinket.io/embed/python/273d008079

Exercise: Explore the
Code:
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.

Code:
a = ['Alice', 'Liz', 'Bob'] data = {} for item in a: data[item] = item

How do you accomplish this?

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

Code:
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:
pprint
contains the function
Code:
pprint
. This will ‘pretty print’ your dictionary. It sorts the keys alphabetically and printseach key-value pair on a newline.

Code:
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)
pair of a dictionary like this:

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()
method to obtain the iterable. Then, use a single-line for loop to iterate over it.

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()
method of a dictionary object creates an iterable of
Code:
(key, value)
tuple pairs from the dictionary.

Python Update Dictionary in One Line

Challenge: Given a dictionary and a
Code:
(key, value)
pair. The
Code:
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
Code:
dict[key] = value
to create a new mapping from
Code:
key
to
Code:
value
in the dictionary. There are two cases:
  • The
    Code:
    key
    already existed before and was associated to the old
    Code:
    value_old
    . In this case, the new
    Code:
    value
    overwrites the old
    Code:
    value_old
    after updating the dictionary.

  • The
    Code:
    key
    didn’t exist before in the dictionary. In this case, it is created for the first time and associated to
    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 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:

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 old

Now, 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'] = 20

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

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

You 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 old

The
Code:
age.setdefault('Alice', 20)
only inserts the key
Code:
'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!

The post Python One Line Dictionary first appeared on Finxter.
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: