您的位置:首页 > 编程语言 > Python开发

python 字典套字典或列表

2016-11-16 10:25 253 查看
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']


b25a
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: