How to use string.format with nested dict

I have a nested dict:

KEYS1 = ("A", "B", "C")
KEYS2 = ("X", "Y", "Z")

d = dict.fromkeys(KEYS1, dict.fromkeys(KEYS2, 0))

Now I would like to embed its values ​​in a string using a format, something like

print("d['A']['X']={A,X:d}".format(**d))

for output:

d['A']['X']=0

This does not work. Any suggestions on how to do this correctly?

+4
source share
2 answers
KEYS1 = ("A", "B", "C")
KEYS2 = ("X", "Y", "Z")

d = dict.fromkeys(KEYS1, dict.fromkeys(KEYS2, 0))

print("d['A']['X']={A[X]}".format(**d))

Output:

d['A']['X']=0

From python 3.6, you will be able to access the dict in a string using Literal string interpolation :

In [23]: print(f"d['A']['X']={d['A']['X']}")
d['A']['X']=0
+6
source

You can use the str.formatopportunity to subscribe to the arguments that you provide.

KEYS1 = ("A", "B", "C")
KEYS2 = ("X", "Y", "Z")

d = dict.fromkeys(KEYS1, dict.fromkeys(KEYS2, 0))

print("d['A']['X']={[A][X]}".format(d))

Padraic Cunningham, ( 1). , {A[X]} , .format , dict d.

, dict 'A', dict 'X'

+1

Source: https://habr.com/ru/post/1621520/


All Articles