Python dict.get() or None scenario [duplicate]

2024/11/19 1:27:47

I am attempting to access a dictionary's values based on a list of keys I have. If the key is not present, I default to None. However, I am running into trouble when the value is an empty string ''. Please see the code below for my examples

dict = {}
dict['key'] = ''
test = dict.get('key')
print(test)
>>

Above is as expected, and the empty string is printed. But now see what happens when I default the dict.get() function to None if the key is not present

dict = {}
dict['key'] = ''
test = dict.get('key') or None
print(test)
>> None

Why does this happen? In the second example the key is present so my intuition says '' should be printed. How does Python apply the 'or' clause of that line of code?

Below is the actual code I'm using to access my dictionary. Note that many keys in the dictionary have '' as the value, hence my problem.

# build values list
params = []
for col in cols:params.append(dict.get(col) or None)

Is there a best solution someone can offer? My current solution is as follows but I don't think it's the cleanest option

# build values list
params = []
for col in cols:if dict.get(col) is not None:params.append(dict.get(col))else:params.append(None)
Answer

You don't need or None at all. dict.get returns None by default when it can't find the provided key in the dictionary.

It's a good idea to consult the documentation in these cases:

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

https://en.xdnf.cn/q/70992.html

Related Q&A

p-values from ridge regression in python

Im using ridge regression (ridgeCV). And Ive imported it from: from sklearn.linear_model import LinearRegression, RidgeCV, LarsCV, Ridge, Lasso, LassoCVHow do I extract the p-values? I checked but rid…

AutoTokenizer.from_pretrained fails to load locally saved pretrained tokenizer (PyTorch)

I am new to PyTorch and recently, I have been trying to work with Transformers. I am using pretrained tokenizers provided by HuggingFace.I am successful in downloading and running them. But if I try to…

How to scroll down in an instagram pop-up frame with Selenium

I have a python script using selenium to go to a given Instagram profile and iterate over the users followers. On the instagram website when one clicks to see the list of followers, a pop-up opens with…

Get starred messages from GMail using IMAP4 and python

I found many dummy info about working with IMAP, but I didnt understand how to use it for my purposes. I found how I can get ALL messages from mailbox and ALL SEEN messages, but how should I work with …

python and php bcrypt

I was using Laravel to register the users. It uses bcrypt like so:$2y$10$kb9T4WXdz5aKLSZX1OkpMOx.3ogUn9QX8GRZ93rd99i7VLKmeoXXXI am currently making another script that will authenticate users from anot…

Python socket library thinks socket is open when its not

Im working with a bit of Python that looks like this:HOST = 127.0.0.1 PORT = 43434 single = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try:single.bind((HOST, PORT)) except socket.error as e:# Pr…

object of type _csv.reader has no len(), csv data not recognized

The following is a self-contained example. Change the "folder_name" to run it. This answers : reader type = _csv.reader list(reader) = [] _csv.reader has no len()I have tried many things but …

Lookup country for GPS coordinates without Internet access

I need to find out in what country given GPS coordinates are, on a device that has no Internet access (e.g. this, but without the easy on-line solution). Having no experience with GIS, I guess Id need …

how to get spyders python recognize external packages on MacOS X?

I have spyderlib installed on my MacOS X (10.6.8) using the official dmg file. In parallel, I have installed packages using both pip and homebrew from the terminal (i.e. opencv, gdal...). As Spyder is …

textcat - architecture extra fields not permitted

Ive been trying to practise what Ive learned from this tutorial:(https://realpython.com/sentiment-analysis-python/) using PyCharm. And this line: textcat.add_label("pos")generated a warning: …