python 字典套字典或列表的示例
更新时间:2019年12月16日 14:36:47 作者:g863402758
今天小编就为大家分享一篇python 字典套字典或列表的示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
文件f1
| A | 1 | a |
| A | 1 | b |
| A | 2 | C |
| B | 2 | a |
| B | 2 | b |
生成如下字典:
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 字典套字典或列表的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
详解python requests中的post请求的参数问题
这篇文章主要介绍了详解python requests中的post请求的参数问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-03-03
python中startswith()和endswith()的用法详解
Python startswith() 方法用于检查字符串是否是以指定子字符串开头,endswith()方法主要是用于判断字符串是否以指定字符或子字符串结尾,常用于判断文件类型,对python startswith()和endswith()用法相关知识感兴趣的朋友一起看看吧2021-10-10


最新评论