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

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

相关文章

使用pandas 将DataFrame转化成dict

直接转换就行了,key为DataFrame的column; import pandas as pd data = pd.read_csv('./input/month_6_1.cs...

python 3.6.4 安装配置方法图文教程

python 3.6.4 安装配置方法图文教程

今天补一下关于如何安装Python的操作步骤: 我的系统是我win系统 64 位 1.第一步先去python的官方网站下载python的安装包:地址 根据自己的系统选择对应的...

Python实现PS滤镜Fish lens图像扭曲效果示例

Python实现PS滤镜Fish lens图像扭曲效果示例

本文实例讲述了Python实现PS滤镜Fish lens图像扭曲效果。分享给大家供大家参考,具体如下: 这里实现 PS 滤镜中的一种几何变换– Fish lens, 对图像做扭曲,感觉就...

python创建关联数组(字典)的方法

本文实例讲述了python创建关联数组(字典)的方法。分享给大家供大家参考。具体分析如下: 关联数组在python中叫字典,非常有用,下面是定义字典的两种方法 # Dictionar...

Python Tkinter模块 GUI 可视化实例

我就废话不多说了,直接上代码: coding:utf-8 #自带的Tkinter模块 from Tkinter import * from ScrolledText impo...