Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refactor my for loop as python dictionary comprehension?

I am using Python 3.6. I wrote following code, it's a for loop:

Edit: I made a mistake when I wrote var l down, so I re-type it here. Thanks for @Ender Look !!

l = [['a','1'], ['a','2'], ['a','3']]
d = {}
for i in l:
    d[i[0]] = d.get(i[0], '') + '\t' + i[1]
print (d)

So, the result is what I want: {'a': '\t1\t2\t3'}

Then I refactor above code as comprehension:

dict2 = {} dict2 = {i[0]: dict2.get(i[0], '') + '\t' + i[1] for i in l} print(dict2)

I though they should return same output. But the dict2 is:

{'a': '\t3'}

I want to know what's the matter with my dict comprehension? Thanks a lot!

like image 602
ywan Avatar asked May 21 '26 08:05

ywan


2 Answers

You don't necessarily need to use a comprehension here. You can make use of defaultdict from collections:

>>> from collections import defaultdict
>>> d = defaultdict(str)
>>> for li in l:
...  d[li[0]] += f'\t{li[1]}'
...
>>> d
defaultdict(<class 'str'>, {'a': '\t1\t2'})
like image 69
idjaw Avatar answered May 22 '26 21:05

idjaw


Your dictionary comprehension doesn't work because it's use .get on itself.

dict2 = {i[0]: dict2.get(i[0], '') + '\t' + i[1] for i in l}

Until the end of the whole dictionary comprehension, this new dictionary isn't assigned to your actual dict2 variable. So all the times your comprehension tries to retrieve the value from dict2.get(...) it always executes that function from the empty dictionary dict2 = {}.

Sadly, I don't know (and I don't think it exists) a way to use .get on a dictionary comprehension about itself, because the variable dict2 isn't updated on "real time" (it wait until the end the comprehension). Or at least that I have understood, my humble knowledge isn't perfect.

like image 38
Ender Look Avatar answered May 22 '26 22:05

Ender Look



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!