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

yipeiwu_com6年前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设计】。

相关文章

将python文件打包成EXE应用程序的方法

将python文件打包成EXE应用程序的方法

相信大家都想把自己完成的项目打包成EXE应用文件,然后就可以放在桌面随时都能运行了,下面来分享利用pytinstaller这个第三方库来打包程序,既简单又快捷,我也试过用其他的方式来打包...

Python优先队列实现方法示例

本文实例讲述了Python优先队列实现方法。分享给大家供大家参考,具体如下: 1. 代码 import Queue import threading class Job(object...

Python常见数据结构详解

本文详细罗列归纳了Python常见数据结构,并附以实例加以说明,相信对读者有一定的参考借鉴价值。 总体而言Python中常见的数据结构可以统称为容器(container)。而序列(如列表...

python 使用matplotlib 实现从文件中读取x,y坐标的可视化方法

python 使用matplotlib 实现从文件中读取x,y坐标的可视化方法

1. test.txt文件,数据以逗号分割,第一个数据为x坐标,第二个为y坐标,数据如下:1.1,2 2.1,2 3.1,3 4.1,5 40,38 42,41 43,42 2....

浅谈python3发送post请求参数为空的情况

post请求的时候如果不带参数,其实作用就跟get请求一样。我们在做接口测试的时候,发现开发就全部使用的post,get的作用就被这样的post空参数请求给替代了。 在Python代码请...