python 生成字典嵌套的 json代码

  最近写脚本用到Python,在网上看到了很多关于如何解析多层嵌套的,但是如何生成一个嵌套的map还是需要看一些python的语法。 
目的:生成{1: {‘errors’: {0: ‘d:\helloworld’, 1: ‘d:\dict’}, ‘os’: ‘windows’, ‘type’: 2}}这样的多层嵌套的数据。 
d1={} 
d1.setdefault(1,{})[errors]={}

用同样的方式设置下一侧的嵌套 
temp = d1[1] 
temp.setdefault(‘errors’,{})[error_len]=’d:\helloworld’

d1.setdefault(key,{})[‘os’]=’windows’

d1.setdefault(key,{})[‘type’]=2

OK,这样就可以生成想要的格式的数据了。


原数据样式:

  date,  fund_code,  fundnav,  net_value,  ticker,  position,  stock_to_nav_rate,  price
2016-02-29,  a,     173674845.18,   0.863,    002131,   448128,    0.0376719426075725,  14.6
2016-02-29,  b, 173674845.18,  0.863,    002312,  127400,    0.01679840276797879,  22.9
2016-02-29,  a,   173674845.18,  0.863,   300038,   16900,     0.00551543315905779, 56.68



def
get_fund_data(path): fund = pd.read_csv(path, dtype='str') fund_data_date = {} stock_to_nav_rates = [] stocks = {} net_values = {} for index, row in fund.iterrows(): date = row['date'] # if date not in days: # nav_rate_data = {} # fund_data = {} # fund_code_data = {} ticker = row['ticker'] stock_to_nav_rate = float(row['price'])*float(row['position'])/float(row['fundnav']) stock_to_nav_rates.append(stock_to_nav_rate) fund_code = row['fund_code'] net_value = row['net_value'] fund_data_date.setdefault(date, {}).setdefault(fund_code, {})['net_value'] = net_value fund_data_date.setdefault(date, {}).setdefault(fund_code, {}).setdefault('stocks', {})[ticker] = stock_to_nav_rate #print('checks',checks) df = pd.read_csv(path,dtype = 'str') df['stock_to_nav_rate']=stock_to_nav_rates print('stock_to_nav_rates',stock_to_nav_rates) df.to_csv(path,index=False) print('stock_to_nav_rates',df) return fund_data_date # fund_data_date: # { # '20160301': { # 'a': { # 'stocks': { # '002131': '0.0379171984' # }, # 'net_value': '0.863' # }, # 'b': { # 'stocks': { # '600600': '0.0059126488', # '000063': '0.0047433996', # '002773': '0.0091912366', # '600276': '0.1375525227' # }, # 'net_value': '0.995' # } # }, # '20160302': { # 'a': { # 'stocks': { # '002131': '0.0396483171' # }, # 'net_value': '0.864' # }, # 'b': { # 'stocks': { # '600600': '0.0061313204', # '000063': '0.0050591882', # '002773': '0.0094754688', # '600276': '0.1404317134' # }, # 'net_value': '0.999' # } # } # }

 

posted on 2017-06-05 18:26  小鸟的士林  阅读(595)  评论(0)    收藏  举报

导航