Python处理Dict生成json
问题描述
情况是这样:json文件中存在一个值为
'headers':{ 'connection':['close'], 'content_language':['en'], 'content_length':['3137'], 'content_type':['text/html'], 'server':['squid/3.1.23'], 'unknown':[ {'key':'mime_version','value':['1.0']}, {'key':'date','value':['Sat, 25 Mar 2017 06:11:38 GMT']}, {'key':'x_squid_error','value':['ERR_INVALID_URL 0']}, {'key':'x_cache','value':['MISS from unknown']}, {'key':'x_cache_lookup','value':['NONE from unknown:8080']} ]}
由于之前的脚本的处理过于简单粗暴。现实要将'unknown'给替换成字典中的值。以下是我处理的一段Test code ,在Ipython中:
import jsonf = open(’file.json’,’r’)test_line = f.readline()jsonstr = json.loads(test_line)he = jsonstr[’headers’]# 输出正常的for (k,v) in he.items(): print k,’:’,v[0]
输出的是:
'connection':'close', 'content_language':'en', 'content_length':'3137', 'content_type':'text/html', 'server':'squid/3.1.23', 'unknown':[ {'value':['1.0'],'key':'mime_version'}
问题:1, 怎么处理“unknown”中的list,用for的话,怎么输出?2, 怎么处理“unknown”使其能输出如下的结果:
'connection':'close', 'content_language':'en', 'content_length':'3137', 'content_type':'text/html', 'server':'squid/3.1.23', 'mime_version':'1.0', 'date':'Sat, 25 Mar 2017 06:11:38 GMT', 'x_squid_error':'ERR_INVALID_URL 0', 'x_cache':'MISS from unknown', 'x_cache_lookup':'NONE from unknown:8080'
谢谢!~
问题解答
回答1:# 无非就是list套dict,一层一层往下写就是了# 输出正常的for (k,v) in he.items(): if k != ’unknown’:print k,’:’,v[0] else:# unknown对应的值是listfor it in v: # it是dict print it.get(’key’), ’:’, it.get(’value’)[0]回答2:
要学会优雅的处理数据,只要把unknown 取出来再合并进去就行了。
unknown = headers[’unknown’]headers.pop(’unknown’)set(map(lambda x: (x[’key’], x[’value’][0])))headers = dict(headers.items() + unknown)回答3:
headers.update({_[’key’]: _[’value’][0] for _ in headers[’unknown’]})headers.pop(’unknown’)print headers
相关文章: