473,883 Members | 1,637 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String formatting with nested dictionaries

I've got a bit of code which has a dictionary nested within another
dictionary. I'm trying to print out specific values from the inner
dict in a formatted string and I'm running into a roadblock. I can't
figure out how to get a value from the inner dict into the string. To
make this even more complicated this is being compiled into a large
string including other parts of the outer dict.

mydict = {'inner_dict':{ 'Value1':1, 'Value2':2}, 'foo':'bar',
'Hammer':'nails '}

print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
in %(Hammer)s" % mydict

The above fails looking for a key named 'inner_dict['Value1']' which
doesn't exist.

I've looked through the docs and google and can't find anything
relating to this.

Aug 24 '06 #1
5 5586
li*****@gmail.c om schrieb:
I've got a bit of code which has a dictionary nested within another
dictionary. I'm trying to print out specific values from the inner
dict in a formatted string and I'm running into a roadblock. I can't
figure out how to get a value from the inner dict into the string. To
make this even more complicated this is being compiled into a large
string including other parts of the outer dict.

mydict = {'inner_dict':{ 'Value1':1, 'Value2':2}, 'foo':'bar',
'Hammer':'nails '}

print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
in %(Hammer)s" % mydict

The above fails looking for a key named 'inner_dict['Value1']' which
doesn't exist.

I've looked through the docs and google and can't find anything
relating to this.
Because it is not supported. You can only use one level of keys, and it
must be strings. So you have to do it like this:
print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to
poundin %(Hammer)s" % dict(Hammer=myd ict['Hammer'],
Value1=mydict["inner_dict "]["Value1"],
Value2=mydict["inner_dict "]["Value2"])
Diez

Aug 24 '06 #2
At Thursday 24/8/2006 13:22, li*****@gmail.c om wrote:
>I've got a bit of code which has a dictionary nested within another
dictionary. I'm trying to print out specific values from the inner
dict in a formatted string and I'm running into a roadblock. I can't
figure out how to get a value from the inner dict into the string. To
make this even more complicated this is being compiled into a large
string including other parts of the outer dict.

mydict = {'inner_dict':{ 'Value1':1, 'Value2':2}, 'foo':'bar',
'Hammer':'nail s'}

print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
in %(Hammer)s" % mydict

The above fails looking for a key named 'inner_dict['Value1']' which
doesn't exist.
I can think of two ways:

a) Flatten your dictionary. That is, move the contents of inner_dict
onto the outer dict:
mydict.update(m ydict['inner_dict'])
Then use single names for interpolation

b) Do the interpolation in two steps.

template = "foo is set to %(foo)s - Value One is: %(Value1)s
and Value Two is: %(Value2)s -- Hammers are used to pound
in %(Hammer)s"
output = template % mydict['inner_dict']
output = output % mydict

Both methods assume that the inner dict takes precedence in case of
name clashes; reverse the order if you want the opposite.
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 24 '06 #3

Gabriel Genellina wrote:
At Thursday 24/8/2006 13:22, li*****@gmail.c om wrote:
I've got a bit of code which has a dictionary nested within another
dictionary. I'm trying to print out specific values from the inner
dict in a formatted string and I'm running into a roadblock. I can't
figure out how to get a value from the inner dict into the string. To
make this even more complicated this is being compiled into a large
string including other parts of the outer dict.

mydict = {'inner_dict':{ 'Value1':1, 'Value2':2}, 'foo':'bar',
'Hammer':'nails '}

print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
in %(Hammer)s" % mydict

The above fails looking for a key named 'inner_dict['Value1']' which
doesn't exist.

I can think of two ways:

a) Flatten your dictionary. That is, move the contents of inner_dict
onto the outer dict:
mydict.update(m ydict['inner_dict'])
Then use single names for interpolation

b) Do the interpolation in two steps.

template = "foo is set to %(foo)s - Value One is: %(Value1)s
and Value Two is: %(Value2)s -- Hammers are used to pound
in %(Hammer)s"
output = template % mydict['inner_dict']
output = output % mydict

Both methods assume that the inner dict takes precedence in case of
name clashes; reverse the order if you want the opposite.
Gabriel Genellina
Softlab SRL
Thanks, I started going with a) only doing it the long way.
(mydict['Value1'] = mydict['inner_dict']['Value1']) mydict.update() is
*much* simpler and less prone to errors too.

Aug 24 '06 #4
li*****@gmail.c om wrote:
I've got a bit of code which has a dictionary nested within another
dictionary. I'm trying to print out specific values from the inner
dict in a formatted string and I'm running into a roadblock. I can't
figure out how to get a value from the inner dict into the string. To
make this even more complicated this is being compiled into a large
string including other parts of the outer dict.

mydict = {'inner_dict':{ 'Value1':1, 'Value2':2}, 'foo':'bar',
'Hammer':'nails '}

print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
in %(Hammer)s" % mydict

The above fails looking for a key named 'inner_dict['Value1']' which
doesn't exist.
the % operator treats the keys as plain keys, not expressions. if you
trust the template provider, you can use a custom wrapper to evaluate
the key expressions:

mydict = {'inner_dict':{ 'Value1':1, 'Value2':2}, 'foo':'bar',
'Hammer':'nails '}

class wrapper:
def __init__(self, dict):
self.dict = dict
def __getitem__(sel f, key):
try:
return self.dict[key]
except KeyError:
return eval(key, self.dict)

print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
in %(Hammer)s" % wrapper(mydict)

foo is set to bar - Value One is: 1 and Value Two is: 2 -- Hammers are
used to pound in nails

</F>

Aug 24 '06 #5
Le jeudi 24 août 2006 21:02, Fredrik Lundh a écrit*:
class wrapper:
* * *def __init__(self, dict):
********self.di ct = dict
* * *def __getitem__(sel f, key):
********try:
******** * *return self.dict[key]
********except KeyError:
*******
Quite the same idea, but without eval and the need to know the internal dict
arborescence :

In [242]: class nested_dict_wra pper :
.....: def __init__(self, dic) :
.....: self._all = [dic] + [nested_dict_wra pper(v) for v in
dic.values() if isinstance(v, dict)]
.....: def __getitem__(sel f, v) :
.....: for i in self._all :
.....: try : return i[v]
.....: except KeyError: pass
.....: raise KeyError(v + ' not found in dict and subdicts')
.....:
.....:

In [248]: complex_dict = { '0': 'zero', '1':'one', 'in1' : {'2':'two'}, 'in2':
{'3': 'three', '4' :'four', 'deeper':{'5':' five', '6':'six'}}, '7':'seven' }

In [250]: "%%(%s)s "*7 % tuple(range(7)) % nested_dict_wra pper(complex_di ct)
Out[250]: 'zero one two three four five six '

In [251]: "%%(%s)s "*8 % tuple(range(8)) % nested_dict_wra pper(complex_di ct)
Out[251]: 'zero one two three four five six seven '

In [252]: "%%(%s)s "*9 % tuple(range(9)) % nested_dict_wra pper(complex_di ct)
---------------------------------------------------------------------------
exceptions.KeyE rror Traceback (most recent
call last)

/home/maric/<ipython console>

/home/maric/<ipython consolein __getitem__(sel f, v)

KeyError: '8 not found in dict and subdicts'
--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Aug 24 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1698
by: Kamilche | last post by:
I want to convert a dict into string form, then back again. After discovering that eval is insecure, I wrote some code to roll a Python object, dict, tuple, or list into a string. I've posted it below. Does anyone know an easier way to accomplish this? Essentially, I want to avoid doing an 'eval' on a string to get it back into dict form... but still allow nested structures. (My current code doesn't handle nested structures.) I conked...
5
3030
by: Thomas Philips | last post by:
Consider the following simple dictionary e={1:'one', 2: 'two'} e >>>'one' However, If I attempt to print e using a formatted string print " %(1)s" %e, I get a KeyError: '1'
6
2574
by: Andy Baker | last post by:
Hi there, I'm learning Python at the moment and trying to grok the thinking behind it's scoping and nesting rules. I was googling for nested functions and found this Guido quote: (http://www.python.org/search/hypermail/python-1993/0343.html) "This is because nested function definitions don't have access to the local variables of the surrounding block -- only to the globals of the
2
1660
by: Ann Huxtable | last post by:
Hi, I have a nested object (containing dictionaries) that i want to be able to persist (and read back from) a configuration file. Anyone has any ideas/pointers as to how to go about this. Essentially, my objects are dictioanies of dictionaries, and I want to be able to persist their state to text. Any help will be greatly appreciated. thanks
2
2023
by: techiepundit | last post by:
I'm parsing some data of the form: OuterName1 InnerName1=5,InnerName2=7,InnerName3=34; OuterName2 InnerNameX=43,InnerNameY=67,InnerName3=21; OuterName3 .... and so on.... These are fake names I've made up to illustrate the point more clearly. (the embedded device device can't produce XML and this is what I have
8
13385
by: Brian L. Troutwine | last post by:
I've got a problem that I can't seem to get my head around and hoped somebody might help me out a bit: I've got a dictionary, A, that is arbitarily large and may contains ints, None and more dictionaries which themselves may contain ints, None and more dictionaries. Each of the sub-dictionaries is also arbitrarily large. When pretty printing A, in the context I'm using A for, it's rather helpful to remove all key:value pairs where value...
2
2229
by: Benjamin Georgi | last post by:
Hello list, I could use some help extracting the keys/values of a list of dictionaries from a string that is just the str() representation of the list (the problem is related to some flat file format I'm using for file IO). Example: ', 1: }, {0: , 1: , 2: }, {0: }]'
16
1648
by: IamIan | last post by:
Hello, I'm writing a simple FTP log parser that sums file sizes as it runs. I have a yearTotals dictionary with year keys and the monthTotals dictionary as its values. The monthTotals dictionary has month keys and file size values. The script works except the results are written for all years, rather than just one year. I'm thinking there's an error in the way I set my dictionaries up or reference them... import glob, traceback
0
1843
by: d80013 | last post by:
Hello all, I am trying to create a Dictionary of dictionaries in VBA. All I do is declare two dictionaries, one temporary one, and add the temporary dictionary to the main one recursively. The dictionaries are created fine, and i can access their values without any problems. What I want to do however is to pass the (low-level) dictionary to a function and have it access its data. But I can't seem to be able to do that. I have tried...
0
9944
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9793
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10752
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10858
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10420
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9582
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7974
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5996
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4619
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.