嵌套字典赋值问题,急急急
Interface Rx-ok Rx-err Rx-drp Tx-ok Tx-err Tx-drpeth0 250342120 11 620321 0 0
lo 32321 0 0 42121 0 0
wlan0 4211232 900 489 72302233 211 0
处理这个表格文件,
我想把第一列跟第一行的值作为dict的两个维度然后去对应值:
比如a=2503421......
#!/usr/bin/python
# -*- coding: UTF-8 -*-
f = file('data2.txt')
rows=f.readline().split(' ')
lines=f.readlines() #从文件中读取全部行
f.close
columns=[]
for line in lines: #对每一行数据进行处理
data = line.split()
for score in data:
columns.append(score)
print rows,columns
lib={}
for line in lines:
for i in range(0,6):
for j in range(0,3):
lib]]=line.split()
print libFile "/Users/tynnlau/PycharmProjects/Python_Learning/PY01/dataprocess.py", line 23, in <module> lib]]=line.split()KeyError: 'Rx-ok'
但是那个key好像会有问题,不能这样直接给嵌套字典赋值吗?
#! /usr/bin/env python
import sys
import re
def get_version3():
if sys.version == '2':
return False
return True
def get_input(fin):
bmode = False
if 'b' in fin.mode:
bmode = True
idx = 0
cols = []
retdict = dict()
for l in fin:
if bmode and get_version3():
l = l.decode(encoding='UTF-8')
l = l.rstrip('\r\n')
sarr = re.split('\s+',l)
if idx== 0:
cols.extend(sarr)
else:
jdx = 0
newdict = dict()
for c in cols:
jdx += 1
if jdx >= len(sarr):
continue
newdict = sarr
retdict]= newdict
idx += 1
return retdict
def main():
fin = sys.stdin
retdict = get_input(fin)
print('%s'%(repr(retdict)))
return
main()
#!/usr/bin/python
# -*- coding: UTF-8 -*-
f = file('data2.txt')
inf=
f.close()
x=inf
y= for i,j in enumerate(inf) if i>0]
lib={}
for i,j in enumerate(x):
libx={}
inx= for ii,jj in enumerate(inf) if ii>0]
for iii,jjj in enumerate(inx):
libx]=jjj
lib]=libx
print lib 回复 3# cdbclx
这个work,厉害 本帖最后由 bskay 于 2017-06-07 08:59 编辑
text="""Interface Rx-ok Rx-err Rx-drp Tx-ok Tx-err Tx-drp
eth0 250342120 11 620321 0 0
lo 32321 0 0 42121 0 0
wlan0 4211232 900 489 72302233 211 0"""
d=map(lambda l:l.split(), text.splitlines())
r=dict(map(lambda l: (l,dict(zip(d,l))), d))
参考上面把x,y维度调整过来
b={}
b['Rx-ok']['eth0']
回复 1# gymgod
hi
楼主知道为何赋值的时候会报 Key error的错误吗?想请教下原理
页:
[1]