5

I'm reading in a file and storing the info in a dict as it reads from top to bottom. I don't want to print out in a wrong order compared to the original file.

Also, a very small question: I remember seeing it somewhere a short form of the if and else statement:

if a == 'a':
    a = 'b' ? a = 'c'  

Do you know the exact form?

Thanks.

Lewis Norton
  • 5,971
  • 1
  • 17
  • 28
BPm
  • 2,586
  • 8
  • 31
  • 46

5 Answers5

8
  1. Use an OrderedDict.
  2. a = 'b' if a == 'a' else 'c'
Mark Byers
  • 719,658
  • 164
  • 1,497
  • 1,412
  • my python is 2.4, is that why it doesn't have OrderedDict module? I have collections but no OrderedDict – BPm Sep 26 '11 at 23:27
  • 1
    @BPm: Did you read the bit in bold where it says "**See also** [Equivalent OrderedDict recipe](http://code.activestate.com/recipes/576693/) that runs on Python 2.4 or later."? – Mark Byers Sep 26 '11 at 23:32
1

You can use OrderedDict, or you can store the data in a list and index it with a dict, or store it in a dict and save the keys in a list as you go.

Russell Borogove
  • 16,687
  • 3
  • 37
  • 45
0

I don't know about the dict but the short form you're looking for is the Does Python have a ternary conditional operator?

There's a ternary operator for nearly every language, you can find some example on wikipedia. However, the one in Python is has not the same syntax has the others like explained in the linked SO answer.

Community
  • 1
  • 1
krtek
  • 25,218
  • 5
  • 53
  • 79
0

Python dictionaries are unordered (see here).

For your second question, see this previous answer.

Community
  • 1
  • 1
David Alber
  • 15,924
  • 6
  • 59
  • 67
0

Second answer first: a = 'b' if a == 'a' else 'c' (known as a ternary expression)

First answer second: Use an OrderedDict, which is available from 2.7 on.

If that's not available to you, you can:

Ethan Furman
  • 52,296
  • 16
  • 127
  • 201