1

I have an empty dictionary. The value of each key is to be a list. As I process through my data, I'm trying to add a list entry to a dictionary key's value, including possibly creating the key entry, in one line, and I can't figure out why it's not working.

Single set of data just for the example.

This works. It adds a new key, and adds the first entry in the value list to that key.

dates = dict()
mmdd = '3/24'
year = 2018
# -----------------------
# these three lines look they should be able to be combined
tmp = dates.get(mmdd,[])
tmp.append(year)
dates[mmdd] = tmp
# -----------------------
print(dates)       # {'3/24': [2018]}

This doesn't.

dates = dict()
mmdd = '3/24'
year = 2018
dates[mmdd] = dates.get(mmdd,[]).append(year)
print(dates)       # {'3/24': None}

Why doesn't it work? It appears (to me) to be doing the same thing. Everything before the .append returns a list, either with data in it or empty, and the append should add an entry to the list. It works when done piecemeal, but not when done at one time. What is wrong and/or missing from the above one-liner?

(I understand that the None means that it's actually the first two lines that aren't working, i .e.

tmp = dates.get(mmdd,[]).append(year)

is returning None instead of [2018]. But that isn't helping me figure it out, either.)

(I've played with the one-liner in several ways just to see if I could get it work, e.g. I tried putting an extra set of parens around everything before the .append, same with brackets, etc. I've also searched around but haven't been able to find anything.)

I'm not looking for other ways to solve the problem (I can use defaultdict, etc.). I'm specifically looking for why the above one-liner doesn't work. There's a gap in my python understanding and I want to fill it. I have no doubt it's something immediately intuitive to the most casual observer. Nevertheless, I can't figure it out.

Thanks!

vr8ce
  • 476
  • 2
  • 13

0 Answers0