The most Pythonic way of checking if a value in a dictionary is defined/has zero length

2024/11/19 21:25:26

Say I have a dictionary, and I want to check if a key is mapped to a nonempty value. One way of doing this would be the len function:

mydict = {"key" : "value", "emptykey" : ""}
print "True" if len(mydict["key"]) > 0 else "False"  # prints true
print "True" if len(mydict["emptykey"]) > 0 else "False"  # prints false

However, one can rely on the semantics of Python and how if an object is defined it evaluates to true and leave out the len call:

mydict = {"key" : "value", "emptykey" : ""}
print "True" if mydict["key"] else "False"  # prints true
print "True" if mydict["emptykey"] else "False"  # prints false

However, I'm not sure which is more Pythonic. The first feels "explicit is better than implicit", however the second feels "simple is better than complex".

I also wonder if the leaving out the len call could bite me as the dict I'm working with doesn't necessarily contain strings, but could contain other len-able types (lists, sets, etc). OTOH, in the former (with the len call) if None gets stored as a value the code will blow up, whereas the non-len version will work as expected (will eval to false).

Which version is safer and more Pythonic?

Edit: clarifying assumptions: I know the key is in the dictionary, and I know values will be len-able. I also cannot avoid having zero-length values enter the dictionary.

Edit #2: It seems like people are missing the point of my question. I'm not trying to determine the most Pythonic/safest way of checking if a key is present in a dictionary, I'm trying to check if a value has zero length or not

Answer

If you know the key is in the dictionary, use

if mydict["key"]:...

It is simple, easy to read, and says, "if the value tied to 'key' evaluates to True, do something". The important tidbit to know is that container types (dict, list, tuple, str, etc) only evaluate to True if their len is greater than 0.

It will also raise a KeyError if your premise that a key is in mydict is violated.

All this makes it Pythonic.

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

Related Q&A

What does the --pre option in pip signify?

I saw on this page that pip install neo4j-doc-manager --pre was used. What does the --pre flag mean?

Tracing and Returning a Path in Depth First Search

So I have a problem that I want to use depth first search to solve, returning the first path that DFS finds. Here is my (incomplete) DFS function:start = problem.getStartState()stack = Stack()visited =…

Pandas OHLC aggregation on OHLC data

I understand that OHLC re-sampling of time series data in Pandas, using one column of data, will work perfectly, for example on the following dataframe:>>df ctime openbid 1443654000 1.1170…

Python plotting libraries [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

python elasticsearch client set mappings during create index

I can set mappings of index being created in curl command like this:{ "mappings":{ "logs_june":{ "_timestamp":{ "enabled":"true"},"properties&…

Get Primary Key after Saving a ModelForm in Django

How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact_details view which requires the primary key of the …

f.write vs print f

There are at least two ways to write to a file in python:f = open(file, w) f.write(string)orf = open(file, w) print >> f, string # in python 2 print(string, file=f) # in python 3Is there a d…

How can I send a message to someone with my telegram bot using their Username

I am using the telepot python library, I know that you can send a message when you have someones UserID(Which is a number). I wanna know if it is possible to send a message to someone without having th…

Convert a str to path type?

I am trying to interface with some existing code that saves a configuration, and expects a file path that is of type path.path. The code is expecting that the file path is returned from a pygtk browse…

Partially transparent scatter plot, but with a solid color bar

In Python, with Matplotlib, how to simply do a scatter plot with transparency (alpha < 1), but with a color bar that represents their color value, but has alpha = 1?Here is what one gets, with from…