欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python 字典套字典或列表的示例

时间:2021-08-03 08:59:09|栏目: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+Appium实现京东双十一自动领金币功能

栏    目:Python代码

下一篇:利用setuptools打包python程序的方法步骤

本文标题:python 字典套字典或列表的示例

本文地址:http://www.codeinn.net/misctech/163895.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有