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标准异常和异常处理详解

python提供了两个非常重要的功能来处理python程序在运行中出现的异常和错误。你可以使用该功能来调试python程序。 1.异常处理: 本站Python教程会具体介绍。 2.断言(...

python使用threading.Condition交替打印两个字符

Python中使用threading.Condition交替打印两个字符的程序。 这个程序涉及到两个线程的的协调问题,两个线程为了能够相互协调运行,必须持有一个共同的状态,通过这个状态来...

Python删除Java源文件中全部注释的实现方法

本文实例讲述了Python删除Java源文件中全部注释的实现方法。分享给大家供大家参考,具体如下: 同事想删除一个Java项目中的全部注释,让我帮忙想想办法。 没找不到合适工具,就写了这...

Python3中正则模块re.compile、re.match及re.search函数用法详解

本文实例讲述了Python3中正则模块re.compile、re.match及re.search函数用法。分享给大家供大家参考,具体如下: re模块 re.compile、re.matc...

Python自动化测试工具Splinter简介和使用实例

Splinter 快速介绍官方网站:http://splinter.cobrateam.info/官方介绍:Splinter is an open source tool for tes...