Implement an ordered dictionary in Robot Framework

2019-02-19 10:34发布

问题:

I want to have an ordered dictionary in Robot Framework. Is there any libraries which I can use for this purpose? How can I do that?

回答1:

I am not aware of any library that has a keyword to create an ordered dict, but creating an ordered dict is simple enough.

As of Python 2.7, there is an ordered dictionary available from Python. Robot Framework also defines one that is available in Python/Jython versions prior to 2.7. The Robot Framework OrderedDict has more features than the Python one.

Creating an ordered dict in Robot Framework would look like this:

${od}    Evaluate    collections.OrderedDict()    collections    # Python OrderedDict
${od}    Evaluate    sys.modules['robot.utils'].OrderedDict()    sys    # RF Ordered Dict

In Python, using it would look like this:

# use only one of these
from robot.utils import OrderedDict # RF Ordered Dict
from collections import OrderedDict # Python OrderedDict
od = OrderedDict()

Beware that the keywords from Collections were not designed with ordered dicts in mind. For instance Get Dictionary Keys sorts the keys. To workaround that, you can invoke the keys method directly:

${keys}    Call Method    ${od}    keys

or

${keys}    Set Variable    ${od.keys()}

Similarly, Get Dictionary Items, Get Dictionary Values, and Log Dictionary involve sorting, possibly destroying the order of an OrderedDict.