开发者

How to return keys in original order in a dict

开发者 https://www.devze.com 2023-04-08 19:42 出处:网络
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 origi开发者_JAVA技巧nal file.

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 origi开发者_JAVA技巧nal 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.


  1. Use an OrderedDict.
  2. a = 'b' if a == 'a' else 'c'


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.


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.


Python dictionaries are unordered (see here).

For your second question, see this previous answer.


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:

  • Store the index as part of each value (a pain)
  • Use a previous Ordered Dictionary implementation
0

精彩评论

暂无评论...
验证码 换一张
取 消