Python > マップ(ハッシュ、連想配列)

更新日 2019-12-22
広告
マップ(連想配列)の使い方について紹介します。
# マップの宣言
testmap = {}

# キー・バリューの追加
testmap.update({'a': 5})
testmap.update({8: 80})

print testmap['a'] # -> 5
print testmap[8]   # -> 80
print testmap.keys()   # -> ['a', 8]
print testmap.values() # -> [5, 80]
print testmap.items()  # -> [('a', 5), (8, 80)]
ループで処理する場合は、以下のようにします。
for key, value in testmap.items():
    # do something
キーでソートするには、以下のようにします。
for key, value in sorted(map.items()):
print key, value
降順(大きい物順)で取得するには、以下のようにします。
for key, value in sorted(dict.items(),reverse=True):
print key,value
pythonのMapは、存在しないキーを取得しようとすると、エラーになります。 has_keyを使えば、キーの存在を確認できます(Python 2の場合)。
if testMap.has_key(key): # trueなら取得する
     value = testMap[key]
Python 3の場合は、has_keyは使えません。代わりに、"key" in "map"という構文でチェックします。
if “someKey” in testMap:
   # do something
マップをdeep copyするには、copyモジュールを使います。
import copy

newMap = copy.deepcopy(testmap)
広告
お問い合わせは sweng.tips@gmail.com まで。
inserted by FC2 system