I have a nested dict:
KEYS1 = ("A", "B", "C")
KEYS2 = ("X", "Y", "Z")
d = dict.fromkeys(KEYS1, dict.fromkeys(KEYS2, 0))
I'd now like to embed its values in a string using format, something like
print("d['A']['X']={A,X:d}".format(**d))
to output:
d['A']['X']=0
That does not work. Any suggestions on how to do this correctly?
Python's dict. values() method can be used to retrieve the dictionary values, which can then be printed using the print() function.
Nested Dictionary: Nesting Dictionary means putting a dictionary inside another dictionary. Nesting is of great use as the kind of information we can model in programs is expanded greatly.
A dictionary can contain dictionaries, this is called nested dictionaries.
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 the string use Literal string interpolation:
In [23]: print(f"d['A']['X']={d['A']['X']}")
d['A']['X']=0
You can take advantage of str.format
's ability to do subscripting on the arguments 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))
This is really similar to Padraic Cunningham's answer, which is also a good and correct way to do it (which is why I +1'd it). The difference is that in his answer, the part of the string {A[X]}
means that the .format
method is looking for a keyword argument, which gets provided by unpacking the dict d
.
In my method, it is expecting a positional argument, which must be a dict with a key 'A'
, which must also be a dict with the key 'X'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With