我有一个具有以下结构的字典:
{1: {'message': u'test', 'user': u'user1'},
2: {'message': u'test2', 'user': u'user2'}}
我想在这个表单中创建一个包含内部字典值的字符串:
string = "<span>test1</span><span>user1</span><br />
<span>test2</span>..."
我已经尝试了dict.keys()
,dict.values()
,(k,v) for k, v in dict
的所有内容,但我无法使其发挥作用。什么是正确的方法?
答案 0 :(得分:4)
>>> 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/>'
答案 1 :(得分:1)
这样的事情怎么样:
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"
或者,更好的python风格
string = '\n'.join( ("<span>"+v['message'] + "</span><span>" + v['user'] + "</span><br />" for v in dod.values()) )
如果您需要对用户进行排序,您可以
ksorted = sort(dod.keys())
for k in ksorted:
v = dod[k]
string = string + "<span>"+v['message'] + "</span><span>" + v['user'] + "</span><br />\n"
答案 2 :(得分:1)
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
答案 3 :(得分:0)
>>> 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>