Python Dict and File--python辞書とファイルの読み書き

9694 ワード

Python Dict and File–python辞書とファイルの読み書き
ラベル(スペース区切り):Python
Dict Hash Table
Pythonのハッシュテーブル構造を辞書と呼ぶ.基本形式はkey:valueのキー値ペアの集合であり,括弧で囲まれている.string数字とturpleはkeyとして、任意のタイプはvalueとして使用できます.inまたはdict.get(key)を使用して、keyが辞書にあるかどうかを確認できます.
## Can build up a dict by starting with the the empty dict {}
## and storing key/value pairs into the dict like this:
## dict[key] = value-for-that-key
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'

print dict  ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}

print dict['a']     ## Simple lookup, returns 'alpha'
dict['a'] = 6       ## Put new key/value into dict
'a' in dict         ## True
## print dict['z']                  ## Throws KeyError
if 'z' in dict: print dict['z']     ## Avoid KeyError
print dict.get('z')  ## None (instead of KeyError)

forループは1つの辞書のすべてのkeyを遍歴することができ、keyの順序は任意である.dict.keysおよびdict.valuesは、すべてのkeyまたはvalueを返します.また、items()は、辞書内のすべてのキー値データを最も効果的に確認する方法である一連の(key,value)tupleを返す.これらのlistは、sorted関数に渡すことができます.
## By default, iterating over a dict iterates over its keys.
## Note that the keys are in a random order.
for key in dict: print key
## prints a g o

## Exactly the same as above
for key in dict.keys(): print key

## Get the .keys() list:
print dict.keys()  ## ['a', 'o', 'g']

## Likewise, there's a .values() list of values
print dict.values()  ## ['alpha', 'omega', 'gamma']

## Common case -- loop over the keys in sorted order,
## accessing each key/value
for key in sorted(dict.keys()):
print key, dict[key]

## .items() is the dict expressed as (key, value) tuples
print dict.items()  ##  [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]

## This loop syntax accesses the whole dict by looping
## over the .items() tuple list, accessing one (key, value)
## pair on each iteration.
for k, v in dict.items(): print k, '>', v
## a > alpha    o > omega     g > gamma

すべてのリストを作成することを避けることができる変異体iterkeys(), itervalues() , iteritems()は、データ量が大きい場合によく使われます.
辞書の最大値のキー値ペアを返します.
temp[vector.keys()[argmax(vector.values())]] = max(vector.values())
      
ll = sorted(dic.iteritems(), key=lambda d:d[1])

       
ll = sorted(dic.iteritems(), key=lambda d:d[0])

Dict Formatting
%オペレータは、辞書のvalueを文字列に置き換えるのに便利です.
hash = {}
hash['word'] = 'garfield'
hash['count'] = 42
s = 'I want %(count)d copies of %(word)s' % hash  # %d for int, %s for string
# 'I want 42 copies of garfield'

A better way to add element to a dict辞書挿入効率方法
例を挙げると、いくつかの要素の数を統計したいと思っています.一般的には、次のような形式を書くことができます.
n = 16
myDict = {}
for i in range(0, n):
    char = 'abcd'[i%4]
    if char in myDict:
        myDict[char] += 1
    else:
         myDict[char] = 1
print(myDict)

ではdicが大きい場合、以下のコードは上記のコードよりずっと効率的です.
n = 16
myDict = {}
for i in range(0, n):
    char = 'abcd'[i%4]
    try:
        myDict[char] += 1
    except KeyError:
         myDict[char] = 1
print(myDict)

Del削除操作delオペレータは、次のような要素を削除します.
var = 6
del var  # var no more!

list = ['a', 'b', 'c', 'd']
del list[0]     ## Delete first element
del list[-2:]   ## Delete last two elements
print list      ## ['b']

dict = {'a':1, 'b':2, 'c':3}
del dict['b']   ## Delete 'b' entry
print dict      ## {'a':1, 'c':3}

Files open()関数は開き、次に読み書き操作に使用できるファイル番号を返します.f = open('name','r')は、ファイルを開いて変数fに渡すことを意味し、読み取り操作を準備し、f.close()で閉じることができます.また、'w'を使用して書き込み、'a'を追加することもできます.特殊な'rU'は、異なる行の末尾文字を'
'
に変換するために使用され、forはファイルの各行を遍歴するのに有効ですが、textファイルにのみ有効であり、バイナリファイルには機能しません.
# Echo the contents of a file
f = open('foo.txt', 'rU')
for line in f:   ## iterates over the lines of the file
print line,    ## trailing , so print does not add an end-of-line char
               ## since 'line' already includes the end-of line.
f.close()

ローを1回読むたびに、メモリの過剰使用を回避できます.f.readlines()methodはファイル全体を読みメモリに追加し、各行からなるlistを返します.一方、f.read()methodはファイル全体を1つの文字列として読みます.書き込み操作にとって、f.write()methodは、開いた出力ファイルにデータを書き込む最も簡単な方法です.または、スクリーンにprint >> f, stringで印刷します.
Files Unicode
codecsモジュールはUnicodeファイルの読み取りをサポートします.
import codecs

f = codecs.open('foo.txt', 'rU', 'utf-8')
for line in f:
# here line is a *unicode* string