Make ordered dict default?












-1















Is it possible to make default dict literal to create ordered dicts not unordered ones?



I would like to type complex nested configs like:



config = {
'train': {
'speed': 0.001,
'initial_values': [1, 2, 3]
},
'model': {
...
}
}


and an idea to write a mess of brackets



config = OrderedDict([(
'train', OrderedDict([(
'speed', 0.001), (
'initial_values', [1, 2, 3])]),(
'model', OrderedDict([(
...


is absolutely unaplicable.



Please no phylosophy about why my wish is bad.





Ok, currently I would write somethong like:



def od(*args):
return OrderedDict([(args[i], args[i+1]) for i in range(0, len(args), 2)])

config = od(
'train', od(
'speed', 0.001,
'initial_values', [1, 2, 3]
),
'model', od(
...
)
)









share|improve this question




















  • 2





    In short no... but read stackoverflow.com/questions/39980323/… for what 3.6+ does along with caveats and more details.

    – Jon Clements
    Nov 24 '18 at 14:25













  • Use Python 3.6+.

    – Klaus D.
    Nov 24 '18 at 14:25











  • "is absolutely unaplicable..." why?

    – RoadRunner
    Nov 24 '18 at 14:34








  • 1





    @RoadRunner to many boilerplate code

    – Dims
    Nov 24 '18 at 14:37
















-1















Is it possible to make default dict literal to create ordered dicts not unordered ones?



I would like to type complex nested configs like:



config = {
'train': {
'speed': 0.001,
'initial_values': [1, 2, 3]
},
'model': {
...
}
}


and an idea to write a mess of brackets



config = OrderedDict([(
'train', OrderedDict([(
'speed', 0.001), (
'initial_values', [1, 2, 3])]),(
'model', OrderedDict([(
...


is absolutely unaplicable.



Please no phylosophy about why my wish is bad.





Ok, currently I would write somethong like:



def od(*args):
return OrderedDict([(args[i], args[i+1]) for i in range(0, len(args), 2)])

config = od(
'train', od(
'speed', 0.001,
'initial_values', [1, 2, 3]
),
'model', od(
...
)
)









share|improve this question




















  • 2





    In short no... but read stackoverflow.com/questions/39980323/… for what 3.6+ does along with caveats and more details.

    – Jon Clements
    Nov 24 '18 at 14:25













  • Use Python 3.6+.

    – Klaus D.
    Nov 24 '18 at 14:25











  • "is absolutely unaplicable..." why?

    – RoadRunner
    Nov 24 '18 at 14:34








  • 1





    @RoadRunner to many boilerplate code

    – Dims
    Nov 24 '18 at 14:37














-1












-1








-1








Is it possible to make default dict literal to create ordered dicts not unordered ones?



I would like to type complex nested configs like:



config = {
'train': {
'speed': 0.001,
'initial_values': [1, 2, 3]
},
'model': {
...
}
}


and an idea to write a mess of brackets



config = OrderedDict([(
'train', OrderedDict([(
'speed', 0.001), (
'initial_values', [1, 2, 3])]),(
'model', OrderedDict([(
...


is absolutely unaplicable.



Please no phylosophy about why my wish is bad.





Ok, currently I would write somethong like:



def od(*args):
return OrderedDict([(args[i], args[i+1]) for i in range(0, len(args), 2)])

config = od(
'train', od(
'speed', 0.001,
'initial_values', [1, 2, 3]
),
'model', od(
...
)
)









share|improve this question
















Is it possible to make default dict literal to create ordered dicts not unordered ones?



I would like to type complex nested configs like:



config = {
'train': {
'speed': 0.001,
'initial_values': [1, 2, 3]
},
'model': {
...
}
}


and an idea to write a mess of brackets



config = OrderedDict([(
'train', OrderedDict([(
'speed', 0.001), (
'initial_values', [1, 2, 3])]),(
'model', OrderedDict([(
...


is absolutely unaplicable.



Please no phylosophy about why my wish is bad.





Ok, currently I would write somethong like:



def od(*args):
return OrderedDict([(args[i], args[i+1]) for i in range(0, len(args), 2)])

config = od(
'train', od(
'speed', 0.001,
'initial_values', [1, 2, 3]
),
'model', od(
...
)
)






python dictionary literals ordereddictionary






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 14:52









petezurich

3,65081834




3,65081834










asked Nov 24 '18 at 14:23









DimsDims

12.5k42145313




12.5k42145313








  • 2





    In short no... but read stackoverflow.com/questions/39980323/… for what 3.6+ does along with caveats and more details.

    – Jon Clements
    Nov 24 '18 at 14:25













  • Use Python 3.6+.

    – Klaus D.
    Nov 24 '18 at 14:25











  • "is absolutely unaplicable..." why?

    – RoadRunner
    Nov 24 '18 at 14:34








  • 1





    @RoadRunner to many boilerplate code

    – Dims
    Nov 24 '18 at 14:37














  • 2





    In short no... but read stackoverflow.com/questions/39980323/… for what 3.6+ does along with caveats and more details.

    – Jon Clements
    Nov 24 '18 at 14:25













  • Use Python 3.6+.

    – Klaus D.
    Nov 24 '18 at 14:25











  • "is absolutely unaplicable..." why?

    – RoadRunner
    Nov 24 '18 at 14:34








  • 1





    @RoadRunner to many boilerplate code

    – Dims
    Nov 24 '18 at 14:37








2




2





In short no... but read stackoverflow.com/questions/39980323/… for what 3.6+ does along with caveats and more details.

– Jon Clements
Nov 24 '18 at 14:25







In short no... but read stackoverflow.com/questions/39980323/… for what 3.6+ does along with caveats and more details.

– Jon Clements
Nov 24 '18 at 14:25















Use Python 3.6+.

– Klaus D.
Nov 24 '18 at 14:25





Use Python 3.6+.

– Klaus D.
Nov 24 '18 at 14:25













"is absolutely unaplicable..." why?

– RoadRunner
Nov 24 '18 at 14:34







"is absolutely unaplicable..." why?

– RoadRunner
Nov 24 '18 at 14:34






1




1





@RoadRunner to many boilerplate code

– Dims
Nov 24 '18 at 14:37





@RoadRunner to many boilerplate code

– Dims
Nov 24 '18 at 14:37












3 Answers
3






active

oldest

votes


















5














No, you can't alter Python syntax, not without altering the CPython source code and recompiling, but then it would not be Python any more.



The best you can do is to upgrade to Python 3.6 or newer, where dictionaries retain insertion order by default. If you must have the full OrderedDict feature set (reordering, reversing, dict views with ordering), then convert those regular dictionaries to OrderedDict objects after the fact:



from collections import OrderedDict
from functools import singledispatch

@singledispatch
def to_ordered_dict(d):
"""Convert dictionaries to OrderedDict objects, recursively

Assumes you want to use current dictionary iteration order; in Python 3.7
and newer that's the same as insertion order (or earlier if on PyPy, or
when using CPython, 3.6 and newer).

"""
return d

@to_ordered_dict.register(dict)
def _dict(d):
return OrderedDict(
(to_ordered_dict(k), to_ordered_dict(v))
for k, v in d.items()
)

@to_ordered_dict.register(list)
@to_ordered_dict.register(tuple)
def _sequence(s):
return type(s)(map(to_ordered_dict, s))

# add additional type registrations for other compound or container types


and then stick to using {...} notation with a config = to_ordered_dict(config) line at the end.






share|improve this answer


























  • Does this not imply that class OrderedDict(dict): is actually obsolete in 3.6+? It is still in github.com/python/cpython/blob/3.7/Lib/collections/__init__.py

    – usr2564301
    Nov 24 '18 at 14:29






  • 2





    @usr2564301: no, it does not! OrderedDict offers functionality above and beyond merely remembering insertion order.

    – Martijn Pieters
    Nov 24 '18 at 14:30











  • Got it! The final paragraph ".. as it offers some additional functionality" in your referred answer 😊

    – usr2564301
    Nov 24 '18 at 14:31



















2














There's no philosophical reason why you shouldn't get to do this, but you may not do it by altering fundamental Python syntax. As mentioned elsewhere Python dictionaries can retain order after 3.6, but if you must use OrderedDict



d = OrderedDict

config = d([(...)])


You can do the same with methods like .update






share|improve this answer



















  • 2





    Even with a single-letter alias you can't avoid having to use a list and tuples for each key-value pair, though.

    – Martijn Pieters
    Nov 24 '18 at 14:29











  • True enough @MartijnPieters

    – Charles Landau
    Nov 24 '18 at 14:30



















1














Although this doesn't directly answer to your question the way you stated it, I guess you really want to have ability to process some configs. I usually prefer saving configs not in python files, but in some structured data format. So if you can admit usage of json you could do the following.



from collections import OrderedDict
import json

result = json.loads(
'''
{
"train": {
"speed": 0.001,
"initial_values": [1, 2, 3]
},
"model": {
"name": "model_name",
"wheight" : 128000
}
}
''',
object_pairs_hook=lambda pairs: OrderedDict(pairs))


This should work even in python 2.7.



And if you have a dedicated file for config then you can do something like



from collections import OrderedDict
import json

with open('settings.conf', 'r') as f:
settings_str = f.read()
settings = json.loads(settings_str, object_pairs_hook=lambda pairs: OrderedDict(pairs))





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53459124%2fmake-ordered-dict-default%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    5














    No, you can't alter Python syntax, not without altering the CPython source code and recompiling, but then it would not be Python any more.



    The best you can do is to upgrade to Python 3.6 or newer, where dictionaries retain insertion order by default. If you must have the full OrderedDict feature set (reordering, reversing, dict views with ordering), then convert those regular dictionaries to OrderedDict objects after the fact:



    from collections import OrderedDict
    from functools import singledispatch

    @singledispatch
    def to_ordered_dict(d):
    """Convert dictionaries to OrderedDict objects, recursively

    Assumes you want to use current dictionary iteration order; in Python 3.7
    and newer that's the same as insertion order (or earlier if on PyPy, or
    when using CPython, 3.6 and newer).

    """
    return d

    @to_ordered_dict.register(dict)
    def _dict(d):
    return OrderedDict(
    (to_ordered_dict(k), to_ordered_dict(v))
    for k, v in d.items()
    )

    @to_ordered_dict.register(list)
    @to_ordered_dict.register(tuple)
    def _sequence(s):
    return type(s)(map(to_ordered_dict, s))

    # add additional type registrations for other compound or container types


    and then stick to using {...} notation with a config = to_ordered_dict(config) line at the end.






    share|improve this answer


























    • Does this not imply that class OrderedDict(dict): is actually obsolete in 3.6+? It is still in github.com/python/cpython/blob/3.7/Lib/collections/__init__.py

      – usr2564301
      Nov 24 '18 at 14:29






    • 2





      @usr2564301: no, it does not! OrderedDict offers functionality above and beyond merely remembering insertion order.

      – Martijn Pieters
      Nov 24 '18 at 14:30











    • Got it! The final paragraph ".. as it offers some additional functionality" in your referred answer 😊

      – usr2564301
      Nov 24 '18 at 14:31
















    5














    No, you can't alter Python syntax, not without altering the CPython source code and recompiling, but then it would not be Python any more.



    The best you can do is to upgrade to Python 3.6 or newer, where dictionaries retain insertion order by default. If you must have the full OrderedDict feature set (reordering, reversing, dict views with ordering), then convert those regular dictionaries to OrderedDict objects after the fact:



    from collections import OrderedDict
    from functools import singledispatch

    @singledispatch
    def to_ordered_dict(d):
    """Convert dictionaries to OrderedDict objects, recursively

    Assumes you want to use current dictionary iteration order; in Python 3.7
    and newer that's the same as insertion order (or earlier if on PyPy, or
    when using CPython, 3.6 and newer).

    """
    return d

    @to_ordered_dict.register(dict)
    def _dict(d):
    return OrderedDict(
    (to_ordered_dict(k), to_ordered_dict(v))
    for k, v in d.items()
    )

    @to_ordered_dict.register(list)
    @to_ordered_dict.register(tuple)
    def _sequence(s):
    return type(s)(map(to_ordered_dict, s))

    # add additional type registrations for other compound or container types


    and then stick to using {...} notation with a config = to_ordered_dict(config) line at the end.






    share|improve this answer


























    • Does this not imply that class OrderedDict(dict): is actually obsolete in 3.6+? It is still in github.com/python/cpython/blob/3.7/Lib/collections/__init__.py

      – usr2564301
      Nov 24 '18 at 14:29






    • 2





      @usr2564301: no, it does not! OrderedDict offers functionality above and beyond merely remembering insertion order.

      – Martijn Pieters
      Nov 24 '18 at 14:30











    • Got it! The final paragraph ".. as it offers some additional functionality" in your referred answer 😊

      – usr2564301
      Nov 24 '18 at 14:31














    5












    5








    5







    No, you can't alter Python syntax, not without altering the CPython source code and recompiling, but then it would not be Python any more.



    The best you can do is to upgrade to Python 3.6 or newer, where dictionaries retain insertion order by default. If you must have the full OrderedDict feature set (reordering, reversing, dict views with ordering), then convert those regular dictionaries to OrderedDict objects after the fact:



    from collections import OrderedDict
    from functools import singledispatch

    @singledispatch
    def to_ordered_dict(d):
    """Convert dictionaries to OrderedDict objects, recursively

    Assumes you want to use current dictionary iteration order; in Python 3.7
    and newer that's the same as insertion order (or earlier if on PyPy, or
    when using CPython, 3.6 and newer).

    """
    return d

    @to_ordered_dict.register(dict)
    def _dict(d):
    return OrderedDict(
    (to_ordered_dict(k), to_ordered_dict(v))
    for k, v in d.items()
    )

    @to_ordered_dict.register(list)
    @to_ordered_dict.register(tuple)
    def _sequence(s):
    return type(s)(map(to_ordered_dict, s))

    # add additional type registrations for other compound or container types


    and then stick to using {...} notation with a config = to_ordered_dict(config) line at the end.






    share|improve this answer















    No, you can't alter Python syntax, not without altering the CPython source code and recompiling, but then it would not be Python any more.



    The best you can do is to upgrade to Python 3.6 or newer, where dictionaries retain insertion order by default. If you must have the full OrderedDict feature set (reordering, reversing, dict views with ordering), then convert those regular dictionaries to OrderedDict objects after the fact:



    from collections import OrderedDict
    from functools import singledispatch

    @singledispatch
    def to_ordered_dict(d):
    """Convert dictionaries to OrderedDict objects, recursively

    Assumes you want to use current dictionary iteration order; in Python 3.7
    and newer that's the same as insertion order (or earlier if on PyPy, or
    when using CPython, 3.6 and newer).

    """
    return d

    @to_ordered_dict.register(dict)
    def _dict(d):
    return OrderedDict(
    (to_ordered_dict(k), to_ordered_dict(v))
    for k, v in d.items()
    )

    @to_ordered_dict.register(list)
    @to_ordered_dict.register(tuple)
    def _sequence(s):
    return type(s)(map(to_ordered_dict, s))

    # add additional type registrations for other compound or container types


    and then stick to using {...} notation with a config = to_ordered_dict(config) line at the end.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 24 '18 at 14:36

























    answered Nov 24 '18 at 14:27









    Martijn PietersMartijn Pieters

    715k13825002312




    715k13825002312













    • Does this not imply that class OrderedDict(dict): is actually obsolete in 3.6+? It is still in github.com/python/cpython/blob/3.7/Lib/collections/__init__.py

      – usr2564301
      Nov 24 '18 at 14:29






    • 2





      @usr2564301: no, it does not! OrderedDict offers functionality above and beyond merely remembering insertion order.

      – Martijn Pieters
      Nov 24 '18 at 14:30











    • Got it! The final paragraph ".. as it offers some additional functionality" in your referred answer 😊

      – usr2564301
      Nov 24 '18 at 14:31



















    • Does this not imply that class OrderedDict(dict): is actually obsolete in 3.6+? It is still in github.com/python/cpython/blob/3.7/Lib/collections/__init__.py

      – usr2564301
      Nov 24 '18 at 14:29






    • 2





      @usr2564301: no, it does not! OrderedDict offers functionality above and beyond merely remembering insertion order.

      – Martijn Pieters
      Nov 24 '18 at 14:30











    • Got it! The final paragraph ".. as it offers some additional functionality" in your referred answer 😊

      – usr2564301
      Nov 24 '18 at 14:31

















    Does this not imply that class OrderedDict(dict): is actually obsolete in 3.6+? It is still in github.com/python/cpython/blob/3.7/Lib/collections/__init__.py

    – usr2564301
    Nov 24 '18 at 14:29





    Does this not imply that class OrderedDict(dict): is actually obsolete in 3.6+? It is still in github.com/python/cpython/blob/3.7/Lib/collections/__init__.py

    – usr2564301
    Nov 24 '18 at 14:29




    2




    2





    @usr2564301: no, it does not! OrderedDict offers functionality above and beyond merely remembering insertion order.

    – Martijn Pieters
    Nov 24 '18 at 14:30





    @usr2564301: no, it does not! OrderedDict offers functionality above and beyond merely remembering insertion order.

    – Martijn Pieters
    Nov 24 '18 at 14:30













    Got it! The final paragraph ".. as it offers some additional functionality" in your referred answer 😊

    – usr2564301
    Nov 24 '18 at 14:31





    Got it! The final paragraph ".. as it offers some additional functionality" in your referred answer 😊

    – usr2564301
    Nov 24 '18 at 14:31













    2














    There's no philosophical reason why you shouldn't get to do this, but you may not do it by altering fundamental Python syntax. As mentioned elsewhere Python dictionaries can retain order after 3.6, but if you must use OrderedDict



    d = OrderedDict

    config = d([(...)])


    You can do the same with methods like .update






    share|improve this answer



















    • 2





      Even with a single-letter alias you can't avoid having to use a list and tuples for each key-value pair, though.

      – Martijn Pieters
      Nov 24 '18 at 14:29











    • True enough @MartijnPieters

      – Charles Landau
      Nov 24 '18 at 14:30
















    2














    There's no philosophical reason why you shouldn't get to do this, but you may not do it by altering fundamental Python syntax. As mentioned elsewhere Python dictionaries can retain order after 3.6, but if you must use OrderedDict



    d = OrderedDict

    config = d([(...)])


    You can do the same with methods like .update






    share|improve this answer



















    • 2





      Even with a single-letter alias you can't avoid having to use a list and tuples for each key-value pair, though.

      – Martijn Pieters
      Nov 24 '18 at 14:29











    • True enough @MartijnPieters

      – Charles Landau
      Nov 24 '18 at 14:30














    2












    2








    2







    There's no philosophical reason why you shouldn't get to do this, but you may not do it by altering fundamental Python syntax. As mentioned elsewhere Python dictionaries can retain order after 3.6, but if you must use OrderedDict



    d = OrderedDict

    config = d([(...)])


    You can do the same with methods like .update






    share|improve this answer













    There's no philosophical reason why you shouldn't get to do this, but you may not do it by altering fundamental Python syntax. As mentioned elsewhere Python dictionaries can retain order after 3.6, but if you must use OrderedDict



    d = OrderedDict

    config = d([(...)])


    You can do the same with methods like .update







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 24 '18 at 14:28









    Charles LandauCharles Landau

    2,6931216




    2,6931216








    • 2





      Even with a single-letter alias you can't avoid having to use a list and tuples for each key-value pair, though.

      – Martijn Pieters
      Nov 24 '18 at 14:29











    • True enough @MartijnPieters

      – Charles Landau
      Nov 24 '18 at 14:30














    • 2





      Even with a single-letter alias you can't avoid having to use a list and tuples for each key-value pair, though.

      – Martijn Pieters
      Nov 24 '18 at 14:29











    • True enough @MartijnPieters

      – Charles Landau
      Nov 24 '18 at 14:30








    2




    2





    Even with a single-letter alias you can't avoid having to use a list and tuples for each key-value pair, though.

    – Martijn Pieters
    Nov 24 '18 at 14:29





    Even with a single-letter alias you can't avoid having to use a list and tuples for each key-value pair, though.

    – Martijn Pieters
    Nov 24 '18 at 14:29













    True enough @MartijnPieters

    – Charles Landau
    Nov 24 '18 at 14:30





    True enough @MartijnPieters

    – Charles Landau
    Nov 24 '18 at 14:30











    1














    Although this doesn't directly answer to your question the way you stated it, I guess you really want to have ability to process some configs. I usually prefer saving configs not in python files, but in some structured data format. So if you can admit usage of json you could do the following.



    from collections import OrderedDict
    import json

    result = json.loads(
    '''
    {
    "train": {
    "speed": 0.001,
    "initial_values": [1, 2, 3]
    },
    "model": {
    "name": "model_name",
    "wheight" : 128000
    }
    }
    ''',
    object_pairs_hook=lambda pairs: OrderedDict(pairs))


    This should work even in python 2.7.



    And if you have a dedicated file for config then you can do something like



    from collections import OrderedDict
    import json

    with open('settings.conf', 'r') as f:
    settings_str = f.read()
    settings = json.loads(settings_str, object_pairs_hook=lambda pairs: OrderedDict(pairs))





    share|improve this answer




























      1














      Although this doesn't directly answer to your question the way you stated it, I guess you really want to have ability to process some configs. I usually prefer saving configs not in python files, but in some structured data format. So if you can admit usage of json you could do the following.



      from collections import OrderedDict
      import json

      result = json.loads(
      '''
      {
      "train": {
      "speed": 0.001,
      "initial_values": [1, 2, 3]
      },
      "model": {
      "name": "model_name",
      "wheight" : 128000
      }
      }
      ''',
      object_pairs_hook=lambda pairs: OrderedDict(pairs))


      This should work even in python 2.7.



      And if you have a dedicated file for config then you can do something like



      from collections import OrderedDict
      import json

      with open('settings.conf', 'r') as f:
      settings_str = f.read()
      settings = json.loads(settings_str, object_pairs_hook=lambda pairs: OrderedDict(pairs))





      share|improve this answer


























        1












        1








        1







        Although this doesn't directly answer to your question the way you stated it, I guess you really want to have ability to process some configs. I usually prefer saving configs not in python files, but in some structured data format. So if you can admit usage of json you could do the following.



        from collections import OrderedDict
        import json

        result = json.loads(
        '''
        {
        "train": {
        "speed": 0.001,
        "initial_values": [1, 2, 3]
        },
        "model": {
        "name": "model_name",
        "wheight" : 128000
        }
        }
        ''',
        object_pairs_hook=lambda pairs: OrderedDict(pairs))


        This should work even in python 2.7.



        And if you have a dedicated file for config then you can do something like



        from collections import OrderedDict
        import json

        with open('settings.conf', 'r') as f:
        settings_str = f.read()
        settings = json.loads(settings_str, object_pairs_hook=lambda pairs: OrderedDict(pairs))





        share|improve this answer













        Although this doesn't directly answer to your question the way you stated it, I guess you really want to have ability to process some configs. I usually prefer saving configs not in python files, but in some structured data format. So if you can admit usage of json you could do the following.



        from collections import OrderedDict
        import json

        result = json.loads(
        '''
        {
        "train": {
        "speed": 0.001,
        "initial_values": [1, 2, 3]
        },
        "model": {
        "name": "model_name",
        "wheight" : 128000
        }
        }
        ''',
        object_pairs_hook=lambda pairs: OrderedDict(pairs))


        This should work even in python 2.7.



        And if you have a dedicated file for config then you can do something like



        from collections import OrderedDict
        import json

        with open('settings.conf', 'r') as f:
        settings_str = f.read()
        settings = json.loads(settings_str, object_pairs_hook=lambda pairs: OrderedDict(pairs))






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 24 '18 at 15:29









        RomanRoman

        153111




        153111






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53459124%2fmake-ordered-dict-default%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Costa Masnaga