解压缩字典以进行格式化

时间:2017-10-20 03:45:19

标签: python

我有一个不是最终输出的词典:

mydict = {'yesterday':'2017-10-19','today':'2017-10-20','tomorrow':'2017-10-21'}

我希望将其作为__str__内的提示返回,如:

    def __str__(self):
        return "{}:{}, {}:{}, {}:{}".format(**mydict)
    #just for explaining

如何让它发挥作用?

1 个答案:

答案 0 :(得分:1)

将字典解压缩到format会给出命名参数,因此您还需要为占位符命名;你可能需要:

mydict = {'yesterday':'2017-10-19','today':'2017-10-20','tomorrow':'2017-10-21'}
​
"yesterday:{yesterday}, today:{today}, tomorrow:{tomorrow}".format(**mydict)
# 'yesterday:2017-10-19, today:2017-10-20, tomorrow:2017-10-21'

如果您需要格式化键,请将字典中的键值对展平(除非您最初有一个有序字典,否则不保证顺序),然​​后解压缩:

"{}:{}, {}:{}, {}:{}".format(*(x for kv in mydict.items() for x in kv))
# 'today:2017-10-20, tomorrow:2017-10-21, yesterday:2017-10-19'