How to sort environment variables in python

Question:

I am printing environment variables, but there are not printed in a sorted way :

    for variable in os.environ:
        print("   " + variable + "=" + os.environ.get(variable))

I would like to sort os.environ. I tried to put os.environ in a list(), but the sort function is not working.

Any clue?

Thank you

Asked By: peterphonic

||

Answers:

for name, value in sorted(os.environ.items()):
    print("   " + name + "=" + value)
Answered By: Sven Marnach
print 'n'.join("   %-24s=  %s" % x for x in sorted(os.environ.items()))
Answered By: eyquem
from json import dumps
from os import environ

print(dumps({k: v for k, v in sorted(environ.items())}, indent=2))
Answered By: Christian
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.