views:

87

answers:

4

I want to do something like this:

parsetable = {
              # ...

              declarations: {
                             token: 3 for token in [_id, _if, _while, _lbrace, _println]
                             }.update({_variable: 2}),

              #...
             }

However this doesn't work because update doesn't return anything. Is there any easy way to do this besides writing the entire dict explicitly?

It should be possible using dict() and a list comprehension of tuples + the extra part, but that is awkward.

+2  A: 

I think the approach you mentioned using dict() and a list of tuples is the way I would do it:

dict([(x, 3) for x in [_id, _if, _while, _lbrace, _println]] + [(_variable, 2)])

If you really want to use a dict comprehension you can do something like this:

{ x : 2 if x == _variable else 3
  for x in [_id, _if, _while, _lbrace, _println, _variable] }
Mark Byers
Thanks for the response. I think the dict()/tuple list is actually the way I want to go.
Rob Lourens
+1  A: 

however, just to let you know, if you want update return somethign, you can write a func like:

import copy
def updated_dict(first_dict, second_dict):
    f = copy.deepcopy(first_dict)
    f.update(second_dict)
    return f
Ant
Thanks for the response, I'm using dict()/tuple list for now but I'm very tempted by your/martineau's responses so I'll have to keep considering it.
Rob Lourens
+1  A: 

I'd split it up for clarity then apply @Mark Byers' second suggestion for a dict comprehension:

type2 = [_variable]
type3 = [_id, _if, _while, _lbrace, _println]

parsetable = {
    declarations: { token : 2 if token in type2 else 3 for token in type2+type3 }
}

This makes things very clear and is extensible, while keeping related items together for look up ease and/or modification.

martineau
I'd also get rid of the harcoded magic numbers...
martineau
+1  A: 

Here's something similar to what @Ant mentioned shown applied to your sample data:

def merged_dicts(dict1, *dicts):
    for dict_ in dicts:
        dict1.update(dict_)
    return dict1

parsetable = {
    declarations:
        merged_dicts(
            { token: 3 for token in [_id, _if, _while, _lbrace, _println] },
            { _variable: 2 }
        ),
}

I left the preliminary copy.deepcopy() out since it's unnecessary for usage of this kind.

martineau