開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART III.(Functions and Generators)、Test Your Knowledge: Part IV Exercises 、6.(Dictionary tools)を解いてみる。
その他参考書籍
6.(Dictionary tools)
コード(BBEdit)
sample.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
def addDict(dict1, dict2):
result = {}
for key, value in dict1.items():
result[key] = value
for key, value in dict2.items():
result[key]= value
return result
dict1 = {'a':1, 'b':2}
dict2 = {'c':3, 'd':4, 'e':5}
print(addDict(dict1, dict2))
# 引数の順序を入れ替えても結果は同じ
print(addDict(dict2, dict1))
# 関数の定義で使ったitemsメソッドはdictionaryのメソッドで、
# リストには無いメソッドなので、引数にリストを渡すと例外発生
try:
addDict([1,2], [3,4])
except Exception as err:
print(type(err), err, err.args)
入出力結果(Terminal)
$ ./sample.py
{'e': 5, 'd': 4, 'a': 1, 'c': 3, 'b': 2}
{'e': 5, 'd': 4, 'a': 1, 'c': 3, 'b': 2}
<class 'AttributeError'> 'list' object has no attribute 'items' ("'list' object has no attribute 'items'",)
$
0 コメント:
コメントを投稿