python f-string dengan kamus literal [duplikat]

Dec 30 2020

Bagaimana cara melakukan kamus literal dalam tanda kurung kurawal siku f-string?

d_all = {d:d+2 for d in range(10)}
keys = [2,5]
tmp_dict = {d:d_all[d] for d in keys}
print(f'values: {tmp_dict}')

print(f'keys: {[d for d in keys]}')  # list works
print(f'dict: { {{d:d_all[d] for d in keys}} }'  # ???

Jawaban

2 AWhiteFox Dec 29 2020 at 23:14

Coba ini:

print(f'dict: { {d:d_all[d] for d in keys} }')