Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Walrus operator in dict declaration

I want to use the walrus operator in a dictionary declaration. However the : is propably causing a problem. I have a dictionary declaration nested in a list comprehension, but I don't want to decompose it into a simple for-loop (that would be a lazy answer). Is it even possible?

rows = [
    {
        'words': sorted(row_words, key=lambda x: x['x0']),
        'top': top := min(map(lambda x: x['top'], row_words)),
        'doctop': top + doctop_adj,
    } for row_words in doctop_clusters
]

Also this could be useful in some simple scenario.

foo = {
    'a': a := some_calculation(),
    'b': a * 8
}

NOTE: walrus operator in dict comprehension doesn't answer my question because I don't have a condition where I can use the walrus operator. And the following approach is very unclean.

rows = [
    {
        'words': sorted(row_words, key=lambda x: x['x0']),
        'top': top,
        'doctop': top + doctop_adj,
    } for row_words in doctop_clusters 
    if top := min(map(lambda x: x['top'], row_words)) or True
]
like image 866
the Radek Avatar asked Feb 28 '26 06:02

the Radek


1 Answers

As @Sayse pointed out in the comments, the trick is to wrap it in parentheses ().

So the solution for the general scenario is simply:

foo = {
    'a': (a := some_calculation()),
    'b': a * 8
}
like image 92
the Radek Avatar answered Mar 01 '26 18:03

the Radek