In Python How Do You Avoid the Inelegant Dictionary Key-Check Logic?

Problem scenario
You try this prog1.py:

book = {}
book[”apple”] = 5
var1 = book[”orange”]

It returns this:

Traceback (most recent call last):
File “prog1.py”, line 3, in
var1 = book[“orange”]
KeyError: ‘orange’

You often see a couple lines of code check if a key exists in a dictionary before a specific action. You want to avoid this and write Python in a more elegant fashion.

Why Would You Use the enumerate Keyword with a dictionary in Python?

Problem scenario
You see a dictionary used with the enumerate reserved word in Python.

Here is an example:


good_dict = {}
good_dict[”size”] = “medium”
good_dict[”quantity”] = “80”
good_dict[”location”] = “New_York”
good_dict[”phone”] = “555-555-5555”

for idx1, good_key in enumerate(good_dict):

Solution
A counter (a unique integer) can be assigned to each key. For logic-building purposes, it is beneficial. The above snippet would prepare a for loop for logic with 1) integers uniquely being assigned to the keys of the dictionary and 2) the keys of the dictionary.

Why Would You Assign or Copy a list in Python to be a set?

Problem scenario
You are trying to understand some code. You see a variable in Python that represents a list being cast to a set.

You see something like this in a Python program:

example = [1, 1, 2, 2, 3, 3]
new_example = set(example)

You are curious why this would be done.

From the IDE you do (and see) the following:

example = [1, …

Python Challenge of the Day (2/17/22)

Problem scenario
You have a program as follows:

class Location:
def __init__(self, country=”US”, state=”CA”, city=”Los Angeles”):
self.country = country
self.state = state
self.city = city

def printer(self):
return [self.country, self.state, self.city]

new_loc = Location(“Mexico”, “Mexico City”, “Mexico City”, “good neighborhood”)
print(new_loc.printer())

Here are your choices of what it could print out:

a. TypeError: init() takes from 1 to 4 positional arguments but 5 were given
b.

Do Ordered Dictionaries in Python Consume More Memory than Regular Dictionaries?

Question
You are considered using ordered dictionaries in Python (e.g., because of the way they handle temporal data). Will your program use more memory this way compared to using a regular dictionary?

Answer
Yes. All things being equal, ordered dictionaries use more memory than normal dictionaries.

# You will see that Python 3’s ordered dictionaries consume more memory than regular dictionaries
# This was adapted from https://lerner.co.il/2019/05/12/python-dicts-and-memory-usage/

import sys
from collections import OrderedDict

x = OrderedDict()
y = {}

for i in range(1, …

How Do You Install GraphQL for Python?

Problem scenario
You want to install GraphQL for Python in Linux. What should you do?

Solution

  1. Install pip3 and venv. (If you need assistance with pip3, see this posting. If you need assistance with venv, see this posting.)
  2. Run these commands:

python3 -m venv to_test
cd to_test
source bin/activate
pip3 install graphql-python
pip3 install flask ariadne flask-sqlalchemy flask-cors …

How Do You Troubleshoot String Manipulation with List Slicing Not Working as You Expect?

Problem scenario
You are taking a slice of a Python string. You know that syntax like var_x[-2:] signifies the penultimate character and the last character of a string (called var_x). But you are only seeing one character — not two. You expect to see two (or a different number of characters than what you are seeing). Why is the snippet printing out fewer characters than you expect?

Possible Solution #1
There could be an invisible “\n” attached to the string (e.g.,

How Do You Get a Multi-line Variable in Python to Be Treated as Lines and Not Characters?

Problem scenario
When a number of lines of text are read from a file, the Python program sees each line as such. When a number of lines of text are in the program itself, that is you use a multi-line variable assignment in a .py program, Python sees the characters individually and does not distinguish between the different lines. The len() function reflects these differences. You want the Python program to read the text in the program as if it were read from the “with open” and “readlines()” function line-by-line — not character-by-character.