我想从嵌套在列表中的字典中打印出每个键值对。所以我正在与之合作:
[{"updated_at":"2011/09/26 22:39:18 +0000","url":"http://diveintopython.net/http_web_services/redirects.html","annotations":[],"user":"name","shared":"yes","tags":"python,handler,opener,urllib2","readlater":"no","created_at":"2011/09/26 22:39:18 +0000","title":"11.7.\xc2\xa0Handling redirects","comments":[],"desc":""},{"updated_at":"2011/09/26 11:09:07 +0000","url":"http://www.polimex.net/sklep/index.php?page=Category&catid=7","annotations":[],"user":"name","shared":"yes","tags":"plastic,snap,buttons,clothing","readlater":"no","created_at":"2011/09/26 11:05:48 +0000","title":"Polimex - Plastic\xc2\xa0accessories","comments":[],"desc":""}]
当我这样做时
from pprint import pprint
data = [{"updated_at":"2011/09/26 22:39:18 +0000","url":"http://diveintopython.net/http_web_services/redirects.html","annotations":[],"user":"name","shared":"yes","tags":"python,handler,opener,urllib2","readlater":"no","created_at":"2011/09/26 22:39:18 +0000","title":"11.7.\xc2\xa0Handling redirects","comments":[],"desc":""},{"updated_at":"2011/09/26 11:09:07 +0000","url":"http://www.polimex.net/sklep/index.php?page=Category&catid=7","annotations":[],"user":"name","shared":"yes","tags":"plastic,snap,buttons,clothing","readlater":"no","created_at":"2011/09/26 11:05:48 +0000","title":"Polimex - Plastic\xc2\xa0accessories","comments":[],"desc":""}]
pprint(data)
我得到的结果与原始列表相同,但是在字符串中
'[{"updated_at":"2011/09/26 22:39:18 +0000","url":"http://diveintopython.net/http_web_services/redirects.html","annotations":[],"user":"name","shared":"yes","tags":"python,handler,opener,urllib2","readlater":"no","created_at":"2011/09/26 22:39:18 +0000","title":"11.7.\xc2\xa0Handling redirects","comments":[],"desc":""},{"updated_at":"2011/09/26 11:09:07 +0000","url":"http://www.polimex.net/sklep/index.php?page=Category&catid=7","annotations":[],"user":"name","shared":"yes","tags":"plastic,snap,buttons,clothing","readlater":"no","created_at":"2011/09/26 11:05:48 +0000","title":"Polimex - Plastic\xc2\xa0accessories","comments":[],"desc":""}]'
如何使数据打印出来看起来像这样?
[
{
"updated_at":"2011/09/26 22:39:18 +0000",
"url":"http://diveintopython.net/http_web_services/redirects.html",
"annotations":[],
"user":"name",
"shared":"yes",
"tags":"python,handler,opener,urllib2",
"readlater":"no",
"created_at":"2011/09/26 22:39:18 +0000",
"title":"11.7.\xc2\xa0Handling redirects",
"comments":[],
"desc":""
},
{
"updated_at":"2011/09/26 11:09:07 +0000",
"url":"http://www.polimex.net/sklep/index.php?page=Category&catid=7",
"annotations":[],
"user":"name",
"shared":"yes",
"tags":"plastic,snap,buttons,clothing",
"readlater":"no",
"created_at":"2011/09/26 11:05:48 +0000",
"title":"Polimex - Plastic\xc2\xa0accessories",
"comments":[],"desc":""
}
]
答案 0 :(得分:3)
一种可能性浮现在脑海中。您是否向pprint
提供了JSON字符串?如果是这样,你应该先解码它:
pprint(json.loads(data))
答案 1 :(得分:1)
它...适合我。 (我剪切并粘贴了你的例子!)你使用的是什么Python和OS?你确定你不小心在某处添加了一些额外的引用吗?
您要打印到终端吗?