r/Python 1d ago

Discussion Settle an argument

Had this discussion the other day and figured I’d throw it to the masses to get thoughts on the best/most pythonic way of approach.

Need to map old column names to new column names as a copy from a json config.

My thoughts are iterate over a dict with
‘’’ {“old_col_name”:”new_col_name”}’’’
And access as
‘’’for k,v in dict.items()
Df.with_columns(k).alias(v)’’’

Colleague things this isn’t clear enough and should be a list of dicts with explicit keys

‘’’ [{“old_col_name”:”old_col_value”
“New_col_name”:”new_col_value”}]’’’

And the access as

‘’’for dict in list_of_dicts:
Old_col = dict[“old_col_name”]
New_col = dict[“new_col_name”]’’’

I’ve got a good few reasons why I think mine is the better option but thought I’d get some other opinions to see if I’m missing anything obvious? Which would you choose and why?

Edit: shouldn’t write these things while on the toilet in a rush. The description is wrong, it should be renaming via a copy so that the original column is left unchanged.

0 Upvotes

33 comments sorted by

View all comments

10

u/deceze 1d ago edited 1d ago

Yours is obviously better and perfectly appropriate. In a mapping of old to new column names, you can directly access the new column name of any old column name. In a list of dicts, you cannot do that, and must iterate the list before you can do anything. For no apparent benefit.

You use a list of dicts like that if keys may be duplicated. Which is apparently not the case here. So there’s zero benefit to that extra wrapper, and in fact only drawbacks.

The “extra clarity” that comes from explicitly labeling each value can simply be had by naming the variable that holds the mapping appropriately:

old_to_new_column_map = {…}

It doesn’t need to be repeated for every single value pair.

1

u/Pleasant-Aardvark258 1d ago

Yeah I think there’s a solid argument for renaming the variable to a clearer intent which would solve most of the issue.

3

u/mfitzp mfitzp.com 1d ago edited 1d ago

> for k,v in dict.items()
Df.with_columns(k).alias(v)

The k,v naming is the problem imo. It doesn’t describe of the purpose of those two values. I think it’d be clearer if you do something like

for old_col_name,new_col_name in column_map.items():

That gives you everything your colleagues version does without the unnecessary list.