python 字典套字典或列表
2016-11-16 10:25
253 查看
python 字典套字典或列表
文件f1
生成如下字典: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
文件f1
A | 1 | a |
A | 1 | b |
A | 2 | C |
B | 2 | a |
B | 2 | 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
相关文章推荐
- python列表和字典的方法总结
- python_20100901_元组列表字典的一点区别
- 简明python教程 --C++程序员的视角(四):容器类型(字符串、元组、列表、字典)和参考
- Python字典按值排序、包含字典的列表按字典值排序的方法
- python列表、元组、字典、字符串操作
- Python中数据结构 列表 元组 字典 序列
- python学习笔记——字符串,列表,字典,集合,数值,sorted
- python学习手册笔记--第8章--列表与字典
- 列表(list)和字典(dict)数据排序 Python
- Dive Into Python 学习记录1-函数/模块导入/字典/列表/元组/字符串分割、连接、格式化/映射list/
- Python列表和字典参数使用
- 《Dive Into Python》笔记:关于字典和列表
- Python 元组、列表、字典、文件
- Python 元组、列表、字典、文件
- python小例子之4 -- 列表(list)和字典(dict)数据排序
- Python 列表和字典的一些方法
- Python笔记——基本数据结构:列表、元组及字典
- Python3基础知识(二)---- 元组、列表、字典、文件
- Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
- Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结