Python字典详解

字典:键值对的集合,该集合以键为索引,同一个键对应一个值,为一个容器类型

举例:检索学生或员工信息

<><>对 键(身份证号码) 值(学生信息)

 

字典操作:

创建字典:

>>> ainfo={'qw':12,'er':34}
>>> binfo=dict([('qw',12),('er',12)])
>>> cinfo=dict([['qw',12],['er',12]])
>>> dinfo=dict(name='Bill',age=56)
>>> ainfo
{'qw': 12, 'er': 34}
>>> binfo
{'qw': 12, 'er': 12}
>>> cinfo
{'qw': 12, 'er': 12}
>>> dinfo
{'name': 'Bill', 'age': 56}

初始化字典:

>>> #fromkeys第一个参数是序列类型
>>> aDict={}.fromkeys(('ycg','sx'),30)
>>> aDict
{'ycg': 30, 'sx': 30}
>>> sorted(aDict)
['sx', 'ycg']

使用两个列表创建

a=['qw','rt','yu']
b=['zx','cv','nm']
fdict=dict(zip(a,b))
print(fdict)

添加项: students["2017"]="qwe"

删除键值对:del students["2017"]

遍历字典:

for key in students:

    print key+','+students[key]

遍历字典的键:

for key in students.keys():

    print key

遍历字典的值:

for value in students.values():

    print value

遍历字典的项:

for item in students.items():

    print item

判断键是否

在字典中:in/not in,返回True或者False

字典作为函数的参数:

>>> def f(arg1,*argt,**argd):
	print(arg1)
	print(argt)
	print(argd)

	
>>> f('q','qq','ww',a1=1,a2=2)
q
('qq', 'ww')
{'a1': 1, 'a2': 2}

字典方法:



字典实例一:查询英文文章中出现字数前5多的单词并以图表形式输出


输入用例:article.txt文件:

don't know what I do now is right, those are wrong, and when I finally Laosi when I know these. So I can do now is to try to do well in everything, and then wait to die a natural death.Sometimes I can be very happy to talk to everyone, can be very presumptuous, but no one knows,  I can make him very happy very happy, but couldn't find the source of happiness, just giggle.

# -*- coding: utf-8 -*-
from math import *
from turtle import *
wordcounts={}#用字典存储单词的数量
countwords = []#将字典中的键值反转存入列表,便于排序
count=5
xscale=30#x轴放大倍数
yscale=20#y轴放大倍数
xlabel=[]#存储单词,用于x轴显示
ylabel=[]#存储单词数量,用于y轴显示
#句子中的标点符号替换为空格
def replacepunctuations(line):
    for ch in line:
        if ch in ",.;'":
            line=line.replace(ch,' ')
    return line

#处理每一行并更新字典
def processline(line):

    words=replacepunctuations(line).split()
    for word in words:
        if word in wordcounts:
            wordcounts[word]+=1
        else:
            wordcounts[word]=1

#(x1,y1)到(x2,y2)画一条线
def drawline(t,x1,y1,x2,y2):
    t.penup()
    t.goto(x1,y1)
    t.pendown()
    t.goto(x2,y2)
#在(x,y)上标注文本
def drawtext(t,x,y,text):
    t.penup()
    t.goto(x,y)
    t.pendown()
    t.write(text)

#画条状图
def drawbar(t,x,y,text):
    x=x*xscale
    y=y*yscale
    drawtext(t,x,y,y/yscale)
    drawtext(t,x,-20,text)
    drawline(t, x - 5, 0, x - 5, y)
    drawline(t, x - 5, y, x + 5, y)
    drawline(t, x + 5, y, x + 5, 0)


def drawgraphy(t):
    drawline(t,0,0,200,0)
    drawline(t,0,0,0,150)
    for i in range(0,count):
        x=i+1
        drawbar(t,x,countwords[i][0],countwords[i][1])

def main():
    f = open("article.txt", "r")
    for line in f:
        processline(line)
    print wordcounts
    xlabel = wordcounts.keys()
    ylabel = wordcounts.values()
    #键值反转并排序
    for [y, x] in wordcounts.items():
        countwords.append([x, y])
    countwords.sort()
    countwords.reverse()

    p=Turtle()
    p.pensize(3)
    p.hideturtle()
    drawgraphy(p)
    done()
main()

输出:


字典实例二:

文件合并实例:

TelInformation.txt
姓名: 电话:
嘻嘻 1333333
男男 82782

EmailInformation.txt

姓名: 邮箱:
嘻嘻 123@163.com
东东 124@qq.com

Information.txt
嘻嘻 1333333 123@163.com
男男 82782 not have email
东东 not have tel 124@qq.com

# -*- coding: utf-8 -*-
from math import *
from turtle import *
def main():
    f1=open("TelInformation.txt","r")
    f2=open("EmailInformation.txt","r")
    f3=open("Information.txt","w")
    f1.readline()
    f2.readline()
    lines1=f1.readlines()
    lines2=f2.readlines()
    dicttel={}
    dictemail={}
    list=[]
    for line in lines1:
        information=line.split()
        dicttel[information[0]]=information[1]
    for line in lines2:
        information = line.split()
        dictemail[information[0]] = information[1]
    for line in dicttel.keys():
        if line in dictemail:
            list.append(line+' '+dicttel[line]+' '+dictemail[line]+'\n')
        else:
            list.append(line + ' ' + dicttel[line] + ' not have email\n')
    for line in dictemail.keys():
        if line not in dicttel:
            list.append(line + ' ' + ' not have tel'+dictemail[line]+'\n')
    f3.writelines(list)
    f1.close()
    f2.close()
    f3.close()
main()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值