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

相关文章

HTML的form表单和django的form表单

HTML的form表单和django的form表单

django的表单系统,分2种 基于django.forms.Form的所有表单类的父类 基于django.forms.ModelForm,可以和模型类绑定的Form 直接用...

TensorFlow利用saver保存和提取参数的实例

TensorFlow利用saver保存和提取参数的实例

在训练循环中,定期调用 saver.save() 方法,向文件夹中写入包含了当前模型中所有可训练变量的 checkpoint 文件。 saver.save(sess, FLAGS.t...

使用Python压缩和解压缩zip文件的教程

python 的 zipfile 提供了非常便捷的方法来压缩和解压 zip 文件。 例如,在py脚本所在目录中,有如下文件: 复制代码 代码如下:readability/readabil...

对python3 sort sorted 函数的应用详解

python3 sorted取消了对cmp的支持。 python3 帮助文档: sorted(iterable,key=None,reverse=False) key接受一个函数,...

深入浅析Python 中的sklearn模型选择

1.主要功能如下: 1.classification分类 2.Regression回归 3.Clustering聚类 4.Dimensionality reduction降维 5.Mo...