python 字典套字典或列表

本文介绍了一种从文件读取数据并将其整理为嵌套字典的方法,该方法适用于处理多层级的数据结构,例如将数据按类别和子类别进行分组。

python 字典套字典或列表

文件f1

A1a
A1b
A2C
B2a
B2b

生成如下字典
tdict={'A':{1:['a','b'], 2:['C']}, 'B':{2:['a','b']} }

In [22]: tdict={}


In [23]: f=open('f1')


In [24]: while True:
    ...:     line=f.readline().strip()
    ...:     if not line:
    ...:         break
    ...:     pos1=line.split()[0]
    ...:     pos2=line.split()[1]
    ...:     pos3=line.split()[2]
    ...:     if pos1 not in tdict:
    ...:         tdict[pos1]={}
    ...:         tdict[pos1][pos2]=[pos3]
    ...:     else:
    ...:         if pos2 not in tdict[pos1]:
    ...:             tdict[pos1][pos2]=[pos3]
    ...:         else:
    ...:             tdict[pos1][pos2].append(pos3)
    ...:


In [25]: f.close()


In [26]: tdict
Out[26]: {'A': {'1': ['a', 'b'], '2': ['C']}, 'B': {'2': ['a', 'b']}}

In [27]: tdict['B']['2']
Out[27]: ['a', 'b']



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值