The pythonic way of creating a dictionary with vocabulary understanding, + 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 does not work because the update does not return anything. Is there an easy way to do this besides writing the entire dict explicitly?

This should be possible with dict () and understanding the list of tuples + optional part, but this is inconvenient.

+3
source share
4 answers

I think the approach you mentioned using dict () and a list of tuples is how I did it:

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

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

{ x : 2 if x == _variable else 3
  for x in [_id, _if, _while, _lbrace, _println, _variable] }
+4
source

, , , somethign, func :

import copy
def updated_dict(first_dict, second_dict):
    f = copy.deepcopy(first_dict)
    f.update(second_dict)
    return f
+1

I would split it for clarity, and then apply the second @Mark Byers clause to understand the dict:

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 extensible while preserving related elements for convenience and / or modification.

+1
source

Here's something similar to what @ Ant shows in the above example, as 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 one copy.deepcopy(), since it is not needed for this kind of use.

+1
source

Source: https://habr.com/ru/post/1769210/


All Articles