简体   繁体   中英

Pythonic way to write create dictionary from dict comprehension, + something else

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.

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] }

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM