Python:dict()を使った文字列、タプル、リストの辞書への変換

スポンサーリンク

dict()を使った文字列、タプル、リストの辞書への変換

dict()を使えば、ふたつの値のシーケンスを辞書に変換できます。

2要素のリストのリスト

>>> tmp = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ]
>>> dict(tmp)
{'a': 'b', 'c': 'd', 'e': 'f'}

2要素のタプルのリスト

>>> tmp = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]
>>> dict(tmp)
{'a': 'b', 'c': 'd', 'e': 'f'}

2要素のリストのタプル

>>> tmp = ( ['a', 'b'], ['c', 'd'], ['e', 'f'] )
>>> dict(tmp)
{'a': 'b', 'c': 'd', 'e': 'f'}

2文字の文字列のリスト

>>> tmp = [ 'ab', 'cd', 'ef' ]
>>> dict(tmp)
{'a': 'b', 'c': 'd', 'e': 'f'}

2文字の文字列のタプル(なお、3文字の場合はエラーになります。)

>>> tmp = ( 'ab', 'cd', 'ef' )
>>> dict(tmp)
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> 
>>> tmp = [ 'abc', 'def', 'ghi' ]
>>> dict(tmp)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: dictionary update sequence element #0 has length 3; 2 is required