My goal is to use the format function to print one value of a dict based on a key known at runtime.
I can do it with the an f-string (first print)
I can do it with a fixed key and the format function (second print)
but I can not do it with a dynamic key and the format function (error)
Is it possible to do this by only modifying the "{self.arr[self.key1]}" part of the third print ?
I can do it with the an f-string (first print)
I can do it with a fixed key and the format function (second print)
but I can not do it with a dynamic key and the format function (error)
Is it possible to do this by only modifying the "{self.arr[self.key1]}" part of the third print ?
#!/usr/bin/python3 class Myclass: def print(self): self.arr={'a1':'v1','a2':'v2'} self.key1='a1' value1=f"{self.arr[self.key1]}" print(value1) print("{self.arr[a1]}".format(self=self)) print("{self.arr[self.key1]}".format(self=self)) Myclass().print()Output:
Output:v1
v1
Error:Traceback (most recent call last):
File "./ch25-.py", line 17, in <module>
Myclass().print()
File "./ch25-.py", line 15, in print
print("{self.arr[self.key1]}".format(self=self))
KeyError: 'self.key1'