views:

55

answers:

4

I have a dictionary with following structure :

{1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}

I'd like to create a string containing values from the inner dictionary in this form :

string = "<span>test1</span><span>user1</span><br />
          <span>test2</span>..."

I've tried everything from dict.keys(), dict.values(), (k,v) for k, v in dict but I cannot make it work. What is the proper way ?

A: 

like this?

>>> d={1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}
>>> l=[]
>>> for k,v in d.iteritems():
...     l.append('%s%s%s' % ('<span>', '</span><span>'.join(v.values()),'</span>'))
... 
>>> print '<br/>\n'.join(l)
<span>test</span><span>user1</span><br/>
<span>test2</span><span>user2</span>
Habbie
+4  A: 
>>> d={1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}

>>> ''.join('<span>%(message)s</span><span>%(user)s</span><br/>' % v for k,v in sorted(d.items()))
u'<span>test</span><span>user1</span><br/><span>test2</span><span>user2</span><br/>'
sdolan
that's very cute ;)
Habbie
It's better to iterate over sorted(d.items()) to preserve right order.
Leonid Shvechikov
@Habbie: haha, yes I suppose so :). @Leonid Shvechikov: Good catch. I've updated the answer.
sdolan
+1  A: 

How about something like this:

dod = {1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}
string = ""
for v in dod.values():
    string = string + "<span>"+v['message'] + "</span><span>" + v['user'] + "</span><br />\n"

Or, in much better python style

string = '\n'.join( ("<span>"+v['message'] + "</span><span>" + v['user'] + "</span><br />" for v in dod.values()) )

If you need the users sorted, you could have

ksorted = sort(dod.keys())
for k in ksorted:
    v = dod[k]
    string = string + "<span>"+v['message'] + "</span><span>" + v['user'] + "</span><br />\n"
highBandWidth
+1  A: 
data = {1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}
strg = "".join(["<span>%s</span><span>%s</span><br />" % (item['message'], item['user']) for item in x.values()])
print strg
daniels