python怎样给字典的键对应的值为字典项的字典赋值
人气:0问题 1:需要得到一个类似{“demo”:{“key”:”value”}}这样格式的字典dic。
dic = dict() dic_temp = dict() dic_temp = {"key":"value"} dic["demo"] = dic_temp
问题 2:创建一个多值映射字典.。
d = {} for key, value in pairs: if key not in d: d[key] = [] d[key].append(value)
问题 3:需要得到一个类似[ { “id”:1,“text” : “Root node”, “children” : [ {“id”:2,”text”:”Child node 1”,”children”:true},”Child node 2”] } ]这样格式的json文本。
import json import codecs import sys reload(sys) sys.setdefaultencoding('utf8') def Format_data(): HY_Info = Search_HYInfo() ChildNodes = Search_ChildNodes() print '开始格式化数据' HY_Nodes = [] for HY_id in ChildNodes.keys(): HY_Node = {} HY_Node['id'] = HY_id if HY_id in HY_Info.keys(): HY_Node['text'] = HY_Info[HY_id].decode('gbk')+'('+str(HY_id)+')' else: HY_Node['text'] = '--' print HY_Node['text'] HY_Node['children'] =[] for child_id in ChildNodes[HY_id]: child_Node = {} child_Node['id'] = child_id if child_id in HY_Info.keys(): child_Node['text'] = HY_Info[child_id].decode('gbk') + '('+str(child_id) + ')' else: child_Node['text'] = '--' if child_id in ChildNodes.keys(): child_Node['children'] = True else: child_Node['children'] = False HY_Node['children'].append(child_Node) HY_Nodes.append(HY_Node) json_data = json.dumps(HY_Nodes,ensure_ascii=False,encoding="gb2312") with codecs.open('./data/Parents_leves.json', "wb", "utf-8") as f: f.write(json_data)
您可能感兴趣的文章:
加载全部内容