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'] 

以上这篇python 字典套字典或列表的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持html中文网。

以上就是python 字典套字典或列表的示例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python