Skip to content
Advertisement

(Python).format() is output incorrectly

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

swaps = {'{}'.format(Element[0]): random.choice(('{ff}')).format(ff = Element[1:])}
print(swaps)

If you run

{'abc1':'f'}

Come out like this or

ValueError: Single'}' encountered in format string`

It comes out like this

What I want is that the elements except abc1 are inserted as ff and a randomly selected value is output. For example

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'}

Advertisement

Answer

Given your desired output, you are looking to create new dictionaries, not string representations of dictionaries, so this will do:

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

If you still need a string representation of the dictionary you can get it with

str(swaps)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement