python如何给字典的键对应的值为字典项的字典赋值

时间:2022-11-09 15:33:35

问题 1:需要得到一个类似{“demo”:{“key”:”value”}}这样格式的字典dic。

?
1
2
3
4
dic = dict()
dic_temp = dict()
dic_temp = {"key":"value"}
dic["demo"] = dic_temp

问题 2:创建一个多值映射字典.。

?
1
2
3
4
5
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文本。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/my_xxh/article/details/80274219