字典

字典

通常,一个Python字典的定义方式为:使用花括号裹住逗号分隔的“key:value”对。键必须是不可变的对象(例如字符串、数值或元组),但是值可以是任何的数据类型。键是唯一的,但值不必是唯一的。

python定义一个空的字典和空的集合方法_二进制文件


python定义一个空的字典和空的集合方法_二进制文件_02

dict函数

将一个由两个元素的列表或者两个元素的元组组成的列表转换成一个字典。

list1=[[‘one’,1], [‘two’,2], [‘three’,3]]

或者

list1=[( ‘one’,1), ( ‘two’,2), ( ‘three’,3)]

那么dict(list1)的值为字典{ one’:1,‘two’:2,‘three’:3}

从文本文件中创建字典

如果一个程序要创建一个巨大的字典,那它通常是从一个文件中创建的。

def determine(ageGroup):
    if ageGroup==’child’:
        return 0
    elif ageGroup==’minor’:
        return 5
    elif ageGroup==’adult:
        return 10
    elif ageGroup==’senior’:
        return 8

替换为:

def determine(ageGroup):
    dict={‘child’:0, ’minor’:5, ’adult :10, ’senior’:8}
    return dict[ageGroup]

使用字典作为频率表

统计文件中单词的出现次数,并打印使用频率最高的单词

def  main():
    listOfwords = formListOfWords('py.txt')
    freq = createFrequencyDictionary(listOfwords)
    displayWordCount(listOfwords,freq)
    displayMostCommonWords(freq)

def formListOfWords(fileName):
    infile = open(fileName)
    originalLine = infile.readline().lower()
    line=''
    for ch in originalLine:
        if('a'<=ch<='z') or (ch==' '):
            line+=ch
    listOfwords = line.split()
    return listOfwords

def createFrequencyDictionary(listOfwords):
    freq={}
    for word in listOfwords:
        freq[word] = 0
    for word in listOfwords:
        freq[word] = freq[word] + 1
    return freq

def displayWordCount(listOfwords,freq):
    print('The Gettysburg Address contains',len(listOfwords),'words.')
    print('The Gettysburg Address contains',len(freq),'different words.')
    print()

def displayMostCommonWords(freq):
    print('The most common words and their frequencies are:')
    listOfMostCommonWords = []
    for word in freq.keys():
        if freq[word] >= 2:
            listOfMostCommonWords.append((word,freq[word]))   
    listOfMostCommonWords.sort(key=lambda x:x[1],reverse=True)
    for item in listOfMostCommonWords:
        print(' ',item[0]+':',item[1])

main()

py.txt

A girl who lives next to me never talks to me, because we don't know each other. My mother tells me that the girl goes to the same school with me, but she is ill and has to leave school for a year. Now the girl is better and she keeps to study. I am so surprised, and the girl is such strong that I admire her so much. I want to be friends with her.

在二进制文件中存储字典

文本文件使用字符序列来存储数据。
另外一种称为二进制格式的文件格式,使用字节序列存储数据,它只能被特定的读取器读取。Python拥有可以使用二进制文件存储字典和从二进制文件中获取字典的函数。这些函数必须从一个称为pickle的模块中导入。尽管文本文件对于简单的字典来说够用了,但是通过二进制文件我们可以更加容易地处理最为复杂的字典。
下面几行代码将一个字典存储为二进制文件,其中模式‘wb’代表文件是作为二进制文件为了写入而打开。

import pickle
outfile = open(fileName,’wb’)
pickle.dump(dictionaryName, outfile)
outfile.close()

下面几行代码从一个二进制文件中创建了一个字典,其中模式‘rb’代表二进制文件是为了读入而打开。

infile = open(fileName,’wb’)
dictionaryName = pickle.load(infile)
infile.close()

‘dat’扩展名作为存储字典的二进制文件
如果字典texteseDict已经存储到二进制文件TexteseDict.dat中,并且pickle模块已经被导入,那么函数createDictionary的函数体可以写成

infile = open(fileName,’rb’)
dictionaryName = pickle.load(infile)
infile.close()
return dictionaryName

值为字典的字典

字典的值可以是任何对象类型,包括一个字典。

从字典中获取顺序数据

由于字典是无序结构,它没有sort方法。
使用如下形式的语句,我们可以将字典中的元素按照自定义的顺序存入一个由两个元素的元组组成的列表中:

sorted(dict1.items(),key=f,reverse=BooleanValue):

使用元组作为字典的值

如某一个文件保存了一个总统姓名和他们家乡州的字典。每一个键是形如(last name,first name(s))形式的元组。

字典推导

可以使用字典推导创建字典
{x:x*x for x in range(4)}创建了字典{0:0,1:1,2:4,3:9}

注释

1、字典的键必须作为不可变对象。因此,列表和集合不可以作为键,并且元素是列表或者集合的元素组也不能作为键。
2、字符串、列表、元组以及集合都可以使用pickle模块存储为二进制文件