Python在格式化表达式中对字典进行排序

标签 python string sorting dictionary

我有这个格式化表达式:

def __str__(self): 

        result = "\n".join({("{}: {}").format(key, self.__dict__[key]) for key, value in sorted(self.__dict__.items())}) 

        return result

代码运行但未排序。我不明白为什么它没有被排序。它返回下面的代码,并且每次都以不同的顺序。

currentPL: -438.627395715
portfolio: Balance: 10101
Transactions: 10
exitPrice: 1.14686
exitTime: 2017-07-12 06:0
entryTime: 2017-07-12 06:
currentlyOpen: True
entryPrice: 1.14686
direction: Long
currentPrice: 1.14188
transactionPL: 627.994644
currentPL100: -0.00434229
units: 88077.79030439684

portfolio: Balance: 10101
Transactions: 10
currentPrice: 1.14228
exitTime: 2017-07-12 06:0
entryTime: 2017-07-12 06:
currentlyOpen: True
entryPrice: 1.14686
direction: Long
transactionPL: 627.994644
currentPL100: -0.00399351
currentPL: -403.396279594
exitPrice: 1.14686
units: 88077.79030439684

...

最佳答案

您在集合(无序类型)上调用'\n'.join,这首先违背了排序的最初目的:

您可以使用列表(序列):

"\n".join([...])

或者删除它们并直接使用生成器表达式。这是一个非常可读的版本,使用 itertools.starmap :

from itertools import starmap

result = "\n".join(starmap("{}: {}".format, sorted(self.__dict__.items())) 

关于Python在格式化表达式中对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45062543/

相关文章:

c# - 在 for 循环语句中动态创建属性名称

r - 使用ggplot对同一图中的两个直方图进行排序

python - 打开命令行时Windows环境变量发生变化?

python - 从 python 调用 C 或 C++ 是如何工作的?

python - tkinter 如何使用 pack() 设置标签的位置

string - 如何在dart中使用关系运算符比较日期?

javascript - 用于将字符填充到字符串末尾的jquery函数

python - 限制数组的值

javascript - react / react Hook : child component is not re-rendering after the state is changed?

Android - 更原始的数组仅按一个数组排序