8

I am trying to format a string using an item from a nested dictionary (below)

    people = {
        'Alice': {
            'phone': '2341',
            'addr': '87 Eastlake Court'
            },

        'Beth': {
            'phone': '9102',
            'addr': '563 Hartford Drive'
            },

        'Randy': {
            'phone': '4563',
            'addr': '93 SW 43rd'
            }

        }

From the above (simple) dictionary, I want to format a string to print out Randy's phone extension.

I am able to access all of his details using:

    print("Randy's phone # is %(Randy)s" % people)

But I'm not sure on how to go deeper into the dictionary to single out just the phone number from the dictionary.

I am using Python 3.3, by the way.

Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
KPM
  • 737
  • 4
  • 11
  • 20

1 Answers1

26

Use the new string formatting:

print("Randy's phone # is {0[Randy][phone]}".format(people))

or

print("Randy's phone # is {Randy[phone]}".format(**people))

 

There's no point in passing the entire dictionary if you only use one value.

print("Randy's phone # is {}".format(people['Randy']['phone']))

or

print("Randy's phone # is %s" % people['Randy']['phone'])

will also work.

Passing the dict makes sense if you have a lot of these format strings and do not know which values they use, and want them to be able to access any value.

Or if you use many values in the format string and passing them individually is just too verbose.

Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
  • This is the neatest solution, IMO, but `"Randy's phone # is %s" % people['Randy']['phone']` is marginally more efficient. – Aya Apr 23 '13 at 15:55
  • This is exactly it! Thank you, I wasn't aware of the new string formatting. Inbar presented another valid option: `print("Randy's phone # is %(phone)s" % people['randy'])` Would one be preferred over the other, or considered more 'Pythonic'? – KPM Apr 23 '13 at 15:57
  • Added this comment to answer. – Pavel Anossov Apr 23 '13 at 16:06