Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string.format with nested dict

Tags:

python

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?

like image 569
Oxonon Avatar asked Dec 23 '15 19:12

Oxonon


People also ask

How do you print an entire dictionary in Python?

Python's dict. values() method can be used to retrieve the dictionary values, which can then be printed using the print() function.

What is a nested dictionary explain with an example?

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.

Can a dict contain a dict?

A dictionary can contain dictionaries, this is called nested dictionaries.


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 the string use Literal string interpolation:

In [23]: print(f"d['A']['X']={d['A']['X']}")
d['A']['X']=0
like image 87
Padraic Cunningham Avatar answered Oct 18 '22 15:10

Padraic Cunningham


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'

like image 36
Cody Piersall Avatar answered Oct 18 '22 15:10

Cody Piersall