(Python).format()输出不正确

(Python).format()输出不正确,python,format,Python,Format,如果你跑 Element = ["abc1", "abc2", "abc3", "abc abc abc4", "abc abc5", "abc6"] swaps = {'{}'.format(Element[0]): random.choice(('{ff}')).format(ff = Element[1:])} print(swaps) 像这样或那样出来 {'abc1

如果你跑

Element = ["abc1", "abc2", "abc3", "abc abc abc4", "abc abc5", "abc6"]

swaps = {'{}'.format(Element[0]): random.choice(('{ff}')).format(ff = Element[1:])}
print(swaps)
像这样或那样出来

{'abc1':'f'}
结果是这样的

我想要的是,除了abc1之外的元素被插入为ff,并输出一个随机选择的值。比如说

ValueError: Single'}' encountered in format string`

给定所需的输出,您希望创建新的词典,而不是词典的字符串表示形式,因此这将实现:

swaps = {'{}'.format(Element[0]): random.choice(('{ff}')).format(ff = Element[1:])}
print(swaps)
>>>{'abc1':'abc3'}
print(swaps)
>>>{'abc1':'abc abc5'}
print(swaps)
>>>{'abc1':'abc abc abc4'}
如果您仍然需要字典的字符串表示,可以使用

swaps = {Element[0]: random.choice(Element[1:])}

断然的。非常感谢。
str(swaps)