Python one line dict

Lesson 17: Python Dict Comprehension

Another just as cool (maybe even cooler!) yet lesser known comprehension method after list comprehension is dict comprehension.

Dict Comprehension can be used to create Python dictionaries in one line with a very cool syntax. Sometimes, dict comprehension can achieve what can normally be achieved in many lines with regular syntax. What it does is, it consolidates loops, functions, conditional statements and dictionary additions in a very compact syntax.

Dict comprehension works very similar to List comprehension however there are some differences since dictionary elements consist of 2 items which consists of “key:value” pairs.

Like many concepts in programming, dict comprehension can be explained best with a few examples and mastered best through practicing Python exercises.

Used Where?

Python’s Dict Comprehension method makes compact, custom and tailored dictionary creation a breeze.

It can be used to create dictionaries from lists, tuples, other dictionaries and even range function. It can replace for loop, conditional if statement, map and filter functions in a simple line.

Let’s see some lines that will help you understand this method in detail.

Syntax do(s)

1) Dict Comprehension is made inside the same curly brackets of a dictionary: <>

Читайте также:  Php break scripts and

2) is the default syntax where i:j is the key:value pair, second i is the iterator and dict is your iterable.

Syntax don’t(s)

1) We can’t use brackets for dict comprehension: as [] belongs to list comprehension. Dict comprehension requires curly brackets: <>

A Refresher on Dictionaries and Python Dictionary Syntax

Here is a note to help understand how iteration in dictionaries work and how to avoid confusion before the examples.

Have you ever tried iterating through a dictionary? If not, go ahead and try a simple loop to print each element in a dictionary.

When you try something like:

for i in dictionary:
print(i)

You will see that only the keys are getting printed. What happens is when dictionaries are iterated, only the keys actually get iterated because they are seen as the main element in a dictionary. If you’d like to get the values for keys you can simply use keys to access their values, for example:

for i in dictionary:
print(dictionary[i])

This syntax will print the values of a key only. If you actually wanted both the key and its value as a pair you would have to try something like this which will print both keys and values in a dictionary:

for i in dictionary:
print(i, dictionary[i])

as you may want to make sure dictionary syntax is clearly before proceeding with the rest of this Python lesson.

Источник

Python One Line Dictionary

Be on the Right Side of Change

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) #

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) #

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 = print(data) #

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:

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) ''' '''

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 = # 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 = # 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 dictPython one line dict = 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 .
age = print(f"Alice is years old") # Alice is 19 years old # Alice's Birthday age['Alice'] = 20 print(f"Alice is 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 = print(f"Alice is years old") # Alice is 19 years old # Alice's Birthday if 'Alice' not in age: age['Alice'] = 20 print(f"Alice is 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 = print(f"Alice is years old") # Alice is 19 years old # Alice's Birthday age.setdefault('Alice', 20) print(f"Alice is 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!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. 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?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming 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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Be on the Right Side of Change 🚀

  • The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
  • Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
  • Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.

Learning Resources 🧑‍💻

⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!

Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.

New Finxter Tutorials:

Finxter Categories:

Источник

Оцените статью