• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
[Tut] Python One Line Dictionary

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!

The post Python One Line Dictionary first appeared on Finxter.

https://www.sickgaming.net/blog/2020/09/...ictionary/

 Possibly Related Threads… Thread Author Replies Views Last Post [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 8 10-16-2020, 10:30 PM Last Post: xSicKxBot [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 15 10-10-2020, 08:24 PM Last Post: xSicKxBot [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 16 10-09-2020, 06:13 PM Last Post: xSicKxBot [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 28 10-02-2020, 04:24 AM Last Post: xSicKxBot [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 29 10-01-2020, 02:21 AM Last Post: xSicKxBot [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 31 09-29-2020, 09:02 PM Last Post: xSicKxBot [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 32 09-28-2020, 02:36 AM Last Post: xSicKxBot [Tut] How To Format A String That Contains Curly Braces In Python? xSicKxBot 0 30 09-25-2020, 07:51 PM Last Post: xSicKxBot [Tut] Python Import Error (ModuleNotFoundError) xSicKxBot 0 32 09-20-2020, 04:15 PM Last Post: xSicKxBot [Tut] Python Unicode Encode Error xSicKxBot 0 33 09-19-2020, 03:25 PM Last Post: xSicKxBot

Forum Jump:

Become a Patron!
 Upcoming Events

 Latest Threads News - Review: Horace – A Heart-Warming ... Last Post: xSicKxBot Today 11:38 PM » Replies: 0 » Views: 0 News - Matthew McConaughey Explains The ... Last Post: xSicKxBot Today 10:20 PM » Replies: 0 » Views: 1 PlanetSide 2 External Hack / Mod Last Post: FarCry10 Today 05:27 PM » Replies: 6 » Views: 6811 (Indie Deal) FREE Defense of Roman Brita... Last Post: xSicKxBot Today 03:53 PM » Replies: 0 » Views: 3 AppleInsider - Lowest iPad Pro prices: s... Last Post: xSicKxBot Today 03:19 PM » Replies: 0 » Views: 3 Microsoft - CVP Tom McGuinness: Top take... Last Post: xSicKxBot Today 03:19 PM » Replies: 0 » Views: 3 News - Nintendo First Revealed The Switc... Last Post: xSicKxBot Today 03:19 PM » Replies: 0 » Views: 3 News - Luigi Can Be Unlocked As A Secret... Last Post: xSicKxBot Today 03:19 PM » Replies: 0 » Views: 3 Xbox Wire - Announcing Details for Xbox ... Last Post: xSicKxBot Today 01:19 PM » Replies: 0 » Views: 4 News - Report: China-owned mobile studio... Last Post: xSicKxBot Today 01:19 PM » Replies: 0 » Views: 5