制作或预定义嵌套字典/ JSON的结构||蟒蛇 [英] Making or Predefining Structure of Nested Dictionary/JSON || Python

查看:172
本文介绍了制作或预定义嵌套字典/ JSON的结构||蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入:我有Excel文件,包含3列,Excel文件格式如下:

  ACD 
ACE
AFG
BHJ
BHK
AFI
BLM
BLN
AFO
pre>

我希望通过以下格式从上述输入字体中输入:
输出:

  dictionary = {'A':{'C':['D','E'],'F':['G','I','O']} 'B':{'H':['J','K'],'L':['M','N']}} 

逻辑:对于每个不同的列-1值,需要使嵌套字典&在这个嵌套部分中,对于每个不同的列-2值,需要列出相应的列3值。

解决方案

Edchum
@MYGz

谢谢!但是没有使用大熊猫,我结束了这样做。

从xlrd导入open_workbook 
从nested_dict导入nested_dict

book = open_workbook(input_file_location) #location of excel file
sheet_3 = book.sheets()[2]#sheet_3其中我有数据
data_sheet_3 = [sheet_3.row_values(i)for x in xrange(sheet_3.nrows)]#获取sheet-3的数据
#指定2级嵌套
#format的字典:{'Key1':{'Key2':['Value1','value2']},'Key3' :{'Key4':['Value3','value4']}}
dictionary = nested_dict(2,list)
for row_no in xrange(sheet_3.nrows):
col_1 = data_sheet_3 [row_no] [0]
col_2 = data_sheet_3 [row_no] [1]
col_3 = data_sheet_3 [row_no] [2]
词典[col_1] [col_2] .append(col_3)

打印字典



nested_dict(2,list)是代码允许我指定两个层次的嵌套。



如果你发现更好的或者alt在python中预先定义嵌套字典的结构,请分享示例。


Input: I have Excel file containing 3 columns and format of excel file is like as follow:

A   C   D
A   C   E
A   F   G
B   H   J
B   H   K
A   F   I
B   L   M
B   L   N
A   F   O

I wish to make dictionary from the above input in below format: Output:

dictionary= {'A':{'C':['D','E'],'F':['G','I','O']},'B':{'H':['J','K'],'L':['M','N']}}

Logic: For each distinct column-1 value, need to make nested dictionary & in that nested part, for each distinct column-2 value, need to make list of correspondingly column-3 values.

解决方案

@Edchum @MYGz
Thanks!! But without using pandas, i ended by doing something like this.

from xlrd import open_workbook
from nested_dict import nested_dict

book = open_workbook(input_file_location) # location of excel file 
sheet_3=book.sheets()[2] #sheet_3 in which i have data
data_sheet_3  = [sheet_3.row_values(i) for i in xrange(sheet_3.nrows)] # getting data of sheet-3
# specifying 2-level of nesting
#format of dictionary: {'Key1':{'Key2':['Value1','value2']},'Key3':{'Key4':['Value3','value4']}} 
dictionary=nested_dict(2,list) 
for row_no in xrange(sheet_3.nrows):
        col_1=data_sheet_3[row_no][0]
        col_2=data_sheet_3[row_no][1]
        col_3=data_sheet_3[row_no][2]
        dictionary[col_1][col_2].append(col_3)

print dictionary

nested_dict(2,list) is the main important point in the code which allowed me to specify two levels of nesting.

If you find anything better or alternative of Pre-defining the structure of nested dictionary in python, please share with example.

这篇关于制作或预定义嵌套字典/ JSON的结构||蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆