8

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("{A,X:d}".format(**d))

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

4
  • Could you please explain a little bit more the expected output? Commented Dec 23, 2015 at 19:34
  • d = dict.fromkeys(KEYS1, dict.fromkeys(KEYS2, 0)) - watch out. Every value in the outer dict is the same inner dict, so anything you do to d['A'] will be visible through d['B']. Commented Dec 23, 2015 at 19:39
  • Oh, you're right user2357112 - thanks for catching this. What would you suggest for instantiation of 2 dim storage with keys to zeros? Commented Dec 23, 2015 at 19:41
  • 1
    @Oxonon: Dict comprehension, or dict with a genexp in Python <2.7. {key1: dict.fromkeys(KEYS2, 0) for key1 in KEYS1}, or dict((key1, dict.fromkeys(KEYS2, 0)) for key1 in KEYS1). In cases where the inner values also need to be distinct, you can replace the inner fromkeys with a dict comprehension too. Commented Dec 23, 2015 at 19:44

2 Answers 2

11
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
Sign up to request clarification or add additional context in comments.

1 Comment

Starting in Python 3.8, you can avoid repeating yourself in the f-string version of this code. Just use f"{d['A']['X']=}" (the trailing = sign is the key).
4

You can take advantage of str.format's ability to do subscripting on the arguments you provide.

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. 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'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.