Python辞書及び辞書の基本操作方法の詳細

12372 ワード

この例では、Python辞書および辞書の基本的な操作方法について説明します.皆さんの参考にしてください.具体的には以下の通りです.
辞書は、名前またはキーワードで参照されるデータ構造であり、キーは、マッピングとも呼ばれる数値、文字列、メタグループであってもよい.辞書タイプはPythonで唯一ǖ基本的な操作は以下の通りです.
(1)len():辞書中のキー―値ペアの数を返す.(2)d[k]:キーワードペアの値を返す;(3)d[k]=v:値をキー値kに関連付ける;(4)del d[k]:キー値kの項目を削除する.(5)key in d:キー値keyがdにあるかどうかは、Trueを返し、そうでない場合はFalseを返す.
一、辞書の作成
1.1辞書の直接作成

d={'one':1,'two':2,'three':3}
print d
print d['two']
print d['three']


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
2
3
>>>


1.2 dictによる辞書の作成

# _*_ coding:utf-8 _*_
items=[('one',1),('two',2),('three',3),('four',4)]
print u'items    :'
print items
print u'  dict    ,      :'
d=dict(items)
print d
print u'        :'
print d['one']
print d['three']


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
items    :
[('one', 1), ('two', 2), ('three', 3), ('four', 4)]
  dict    ,      :
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
        :
1
3
>>>


またはキーワードによる辞書の作成

# _*_ coding:utf-8 _*_
d=dict(one=1,two=2,three=3)
print u'      :'
print d
print u'        :'
print d['one']
print d['three']


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
      :
{'three': 3, 'two': 2, 'one': 1}
        :
1
3
>>>


二、辞書のフォーマット文字列

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
print d
print "three is %(three)s." %d


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
three is 3.
>>>


三、辞書の方法
3.1 clear関数:辞書のすべての項目を消去する

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
print d
d.clear()
print d


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
{}
>>>


次の2つの例を見てください
3.1.1

# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
print dd
d={}
print d
print dd

演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two': 2, 'one': 1}
{}
{'two': 2, 'one': 1}
>>>


3.1.2

# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
print dd
d.clear()
print d
print dd


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two': 2, 'one': 1}
{}
{}
>>>


3.1.2と3.1.1の唯一の違いは、辞書dのクリア処理において、3.1.1がdを新しい空辞書に関連付けることであり、この方式は辞書ddに影響を及ぼさないため、辞書dがクリアされた後も、辞書ddの値は変化しない.しかし3.1.2でclearメソッドは辞書dの内容を空にし、clearはdの内容がすべて空になるようにその場で操作する方法であり、ddが指す空間も空にする.
3.2 copy関数:同じキー値を持つ新しい辞書を返します.

# _*_ coding:utf-8 _*_
x={'one':1,'two':2,'three':3,'test':['a','b','c']}
print u'  X  :'
print x
print u'X   Y:'
y=x.copy()
print u'Y  :'
print y
y['three']=33
print u'  Y   ,    :'
print y
print x
print u'  Y   ,    '
y['test'].remove('c')
print y
print x


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
  X  :
{'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1}
X   Y:
Y  :
{'test': ['a', 'b', 'c'], 'one': 1, 'three': 3, 'two': 2}
  Y   ,    :
{'test': ['a', 'b', 'c'], 'one': 1, 'three': 33, 'two': 2}
{'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1}
  Y   ,    
{'test': ['a', 'b'], 'one': 1, 'three': 33, 'two': 2}
{'test': ['a', 'b'], 'three': 3, 'two': 2, 'one': 1}
>>>


注意:コピーされたコピーで値を置換すると、元の辞書には影響しませんが、コピーを変更すると元の辞書も変更されます.deepcopy関数は、コピーの変更によって元の辞書も変化する問題を解決するために、すべての値を含む深いコピーを使用します.

# _*_ coding:utf-8 _*_
from copy import deepcopy
x={}
x['test']=['a','b','c','d']
y=x.copy()
z=deepcopy(x)
print u'  :'
print y
print z
print u'     :'
x['test'].append('e')
print y
print z


演算出力:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
  :
{'test': ['a', 'b', 'c', 'd']}
{'test': ['a', 'b', 'c', 'd']}
     :
{'test': ['a', 'b', 'c', 'd', 'e']}
{'test': ['a', 'b', 'c', 'd']}
>>>


3.3 fromkeys関数:与えられたキーを使用して新しい辞書を作成し、キーのデフォルト値はNone

# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'])
print d


演算出力:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': None, 'two': None, 'one': None}
>>>


またはデフォルトの対応値を指定します.

# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'],'unknow')
print d


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 'unknow', 'two': 'unknow', 'one': 'unknow'}
>>>


3.4 get関数:ディクショナリメンバーへのアクセス

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.get('one')
print d.get('four')


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
1
None
>>>


注意:get関数は、辞書に存在しないキーにアクセスし、そのキーが存在しない場合はNoneを返します.
3.5 has_key関数:辞書に与えられたキーが含まれているかどうかを確認します.

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.has_key('one')
print d.has_key('four')


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
True
False
>>>


3.6 itemsとiteritems関数:itemsはすべての辞書項目をリストで返します.リスト内の項目は(キー、値)から来ています.iteritemsはitemsと似ていますが、リストではなく反復器オブジェクトを返します.

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
list=d.items()
for key,value in list:
  print key,':',value


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
three : 3
two : 2
one : 1
>>>


# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
it=d.iteritems()
for k,v in it:
  print "d[%s]="%k,v


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
d[three]= 3
d[two]= 2
d[one]= 1
>>>


3.7 keysとiterkeys:keys辞書のキーをリスト形式で返し、iterkeysはキーの反復器を返す

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print u'keys  :'
list=d.keys()
print list
print u'
iterkeys :' it=d.iterkeys() for x in it: print x

演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
keys  :
['three', 'two', 'one']
iterkeys  :
three
two
one
>>>


3.8 pop関数:辞書の対応するキーを削除する

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
d.pop('one')
print d


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
{'three': 3, 'two': 2}
>>>


3.9 popitem関数:辞書の項目を削除

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
d.popitem()
print d


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
{'two': 2, 'one': 1}
>>>


3.10 setdefault関数:getメソッドと同様に、所与のキーに関連付けられた値を取得したり、辞書に所与のキーが含まれていない場合に該当するキー値を設定したりすることができます.

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.setdefault('one',1)
print d.setdefault('four',4)
print d


演算結果:

{'three': 3, 'two': 2, 'one': 1}
1
4
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
>>>


3.11 update関数:1つの辞書で別の辞書を更新する

# _*_ coding:utf-8 _*_
d={
  'one':123,
  'two':2,
  'three':3
  }
print d
x={'one':1}
d.update(x)
print d


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 123}
{'three': 3, 'two': 2, 'one': 1}
>>>


3.12 valuesとitervalues関数:valuesは辞書の値をリストで返し、itervaluesは値反復器を返します.辞書の値は一意ではないため、リストに重複する要素を含めることができます.

# _*_ coding:utf-8 _*_
d={
  'one':123,
  'two':2,
  'three':3,
  'test':2
  }
print d.values()


演算結果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
[2, 3, 2, 123]
>>>


Pythonの関連内容についてもっと興味のある読者は、「Python辞書操作技術要約」、「Pythonデータ構造とアルゴリズムチュートリアル」、「Python暗号解読アルゴリズムと技術総括」、「Python符号化操作技術総括」、「Python関数使用技術総括」、「Python文字列操作技術要約」および「Python入門と進級経典チュートリアル」を参照してください.
ここではPythonプログラムの設計に役立つことを願っています.