タプルと辞書と集合

# 辞書の生成

dict01 = {}                     # {}    空辞書
dict02 = {'Japan': 392, 'Korea': 408, 'China': 156, 'Taiwan': 158}

dict03 = dict()                 # {}    空辞書

lst = [('Japan', 392), ('Korea', 408), ('China', 156), ('Taiwan', 158)]
dict04 = dict(lst)

key = ['Japan', 'Korea', 'China', 'Taiwan']
value = [392, 408, 156, 158]
dict05 = dict(zip(key, value))

print('dict01 =', dict01)
print('dict02 =', dict02)
print('dict03 =', dict03)
print('dict04 =', dict04)
print('dict05 =', dict05)

C:>python xxx.py
dict01 = {}
dict02 = {‘Japan’: 392, ‘Korea’: 408, ‘China’: 156, ‘Taiwan’: 158}
dict03 = {}
dict04 = {‘Japan’: 392, ‘Korea’: 408, ‘China’: 156, ‘Taiwan’: 158}
dict05 = {‘Japan’: 392, ‘Korea’: 408, ‘China’: 156, ‘Taiwan’: 158}

# リストのインデックスをキーにした辞書を生成

s = ['春', '夏', '秋', '冬']
season = {k: v for k, v in enumerate(s)}  # {0:'春', 1:'夏', 2:'秋', 3:'冬'}
print(season)

C:>python xxx.py
{0: ‘春’, 1: ‘夏’, 2: ‘秋’, 3: ‘冬’}

# タプルのリスト(全要素がタプルであるリスト)

students = [
    (2012, '福岡太郎'),
    (2013, '長崎龍一'),
    (2011, '熊本紋三'),
]

print(f'students = {students}')
print(f'students[0]    = {students[0]}')
print(f'students[1]    = {students[1]}')
print(f'students[2]    = {students[2]}')
print(f'students[0][0] = {students[0][0]}')
print(f'students[0][1] = {students[0][1]}')
print(f'students[1][0] = {students[1][0]}')
print(f'students[1][1] = {students[1][1]}')
print(f'students[2][0] = {students[2][0]}')
print(f'students[2][1] = {students[2][1]}')

C:>python xxx.py
students = [(2012, ‘福岡太郎’), (2013, ‘長崎龍一’), (2011, ‘熊本紋三’)]
students[0] = (2012, ‘福岡太郎’)
students[1] = (2013, ‘長崎龍一’)
students[2] = (2011, ‘熊本紋三’)
students[0][0] = 2012
students[0][1] = 福岡太郎
students[1][0] = 2013
students[1][1] = 長崎龍一
students[2][0] = 2011
students[2][1] = 熊本紋三

# タプルのリスト(全要素がタプルであるタプル)

students = (
    (2012, '福岡太郎'),
    (2013, '長崎龍一'),
    (2011, '熊本紋三'),
)

print(f'students = {students}')
print(f'students[0]    = {students[0]}')
print(f'students[1]    = {students[1]}')
print(f'students[2]    = {students[2]}')
print(f'students[0][0] = {students[0][0]}')
print(f'students[0][1] = {students[0][1]}')
print(f'students[1][0] = {students[1][0]}')
print(f'students[1][1] = {students[1][1]}')
print(f'students[2][0] = {students[2][0]}')
print(f'students[2][1] = {students[2][1]}')

C:>python xxx.py
students = ((2012, ‘福岡太郎’), (2013, ‘長崎龍一’), (2011, ‘熊本紋三’))
students[0] = (2012, ‘福岡太郎’)
students[1] = (2013, ‘長崎龍一’)
students[2] = (2011, ‘熊本紋三’)
students[0][0] = 2012
students[0][1] = 福岡太郎
students[1][0] = 2013
students[1][1] = 長崎龍一
students[2][0] = 2011
students[2][1] = 熊本紋三

# 季節を表す辞書
# キーは日本語で値は英語

season = {
    '春': 'spring',
    '夏': 'summer',
    '秋': 'autumn',
    '冬': 'winter',
}

print(f"season['春'] = {season['春']}")
print(f"season['夏'] = {season['夏']}")
print(f"season['秋'] = {season['秋']}")
print(f"season['冬'] = {season['冬']}")

C:>python xxx.py
season[‘春’] = spring
season[‘夏’] = summer
season[‘秋’] = autumn
season[‘冬’] = winter

# 季節を表すリスト
# 要素は英語

season = [
    'spring',
    'summer',
    'autumn',
    'winter',
]

print(f'season[0] = {season[0]}')
print(f'season[1] = {season[1]}')
print(f'season[2] = {season[2]}')
print(f'season[3] = {season[3]}')

C:>python xxx.py
season[0] = spring
season[1] = summer
season[2] = autumn
season[3] = winter

# プロ野球選手の永久欠番の辞書(キーが整数値で値が文字列)

retired_number = {
    1: '王 貞治',
    3: '長嶋 茂雄',
    14: '沢村 栄治',
}

print(f'retired_number[1]  = {retired_number[1]}')
print(f'retired_number[3]  = {retired_number[3]}')
print(f'retired_number[14] = {retired_number[14]}')
print(f'retired_number[99] = {retired_number[99]}')     # エラー

C:>python xxx.py
retired_number[1] = 王 貞治
retired_number[3] = 長嶋 茂雄
retired_number[14] = 沢村 栄治
Traceback (most recent call last):
File “C:\xxx.py”, line 12, in
print(f’retired_number[99] = {retired_number[99]}’) # エラー
~~~~~~^^^^
KeyError: 99

# updateメソッドによる辞書の結合(重複なし)

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}
cmy = {'cyan': '水色', 'magenta': '赤紫', 'yellow': '黄'}

# 辞書rgbに辞書cmyを結合
rgb.update(cmy)
print(rgb)

C:>python xxx.py
{‘red’: ‘赤’, ‘green’: ‘緑’, ‘blue’: ‘青’, ‘cyan’: ‘水色’, ‘magenta’: ‘赤紫’, ‘yellow’: ‘黄’}

# updateメソッドによる辞書の結合(重複あり)

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}
cry = {'cyan': '水色', 'red': '紅', 'yellow': '黄'}

# 辞書rgbに辞書cryを結合
rgb.update(cry)
print(rgb)

C:>python xxx.py
{‘red’: ‘紅’, ‘green’: ‘緑’, ‘blue’: ‘青’, ‘cyan’: ‘水色’, ‘yellow’: ‘黄’}

# 演算子|と|=による辞書の結合

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}
cry = {'cyan': '水色', 'red': '紅', 'yellow': '黄'}

print(rgb | cry)
print(cry | rgb)
print()
rgb |= cry
print(rgb)

C:>python xxx.py
{‘red’: ‘紅’, ‘green’: ‘緑’, ‘blue’: ‘青’, ‘cyan’: ‘水色’, ‘yellow’: ‘黄’}
{‘cyan’: ‘水色’, ‘red’: ‘赤’, ‘yellow’: ‘黄’, ‘green’: ‘緑’, ‘blue’: ‘青’}

{‘red’: ‘紅’, ‘green’: ‘緑’, ‘blue’: ‘青’, ‘cyan’: ‘水色’, ‘yellow’: ‘黄’}

# updateメソッドによる辞書の更新

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}

rgb.update(red='紅', blue='紺', yellow='黄')
print(rgb)

C:>python xxx.py
{‘red’: ‘紅’, ‘green’: ‘緑’, ‘blue’: ‘紺’, ‘yellow’: ‘黄’}

# 辞書の全キーをenumerate関数で走査

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}

for i, key in enumerate(rgb):
    print(f'{i} {key}')

C:>python xxx.py
0 red
1 green
2 blue

# 辞書の全キーをenumerate関数で走査(1からカウント)

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}

for i, key in enumerate(rgb, 1):
    print(f'{i} {key}')

C:>python xxx.py
1 red
2 green
3 blue

# 辞書の全キーを走査(インデックス値を使わない)

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}

for key in rgb:
    print(f'{key}')

C:>python xxx.py
red
green
blue

# 辞書のすべてのキー、すべての値、すべての要素をリストとして取り出す

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}

print(f'キー:{list(rgb.keys())}')      # キー      のビューをリストに変換
print(f'値 :{list(rgb.values())}')    # 値        のビューをリストに変換
print(f'要素:{list(rgb.items())}')     # (キー, 値)のビューをリストに変換

C:>python xxx.py
キー:[‘red’, ‘green’, ‘blue’]
値 :[‘赤’, ‘緑’, ‘青’]
要素:[(‘red’, ‘赤’), (‘green’, ‘緑’), (‘blue’, ‘青’)]

# 辞書のすべてのキー、すべての値、すべての要素をタプルとして取り出す

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}

print(f'キー:{tuple(rgb.keys())}')      # キー      のビューをタプルに変換
print(f'値 :{tuple(rgb.values())}')    # 値        のビューをタプルに変換
print(f'要素:{tuple(rgb.items())}')     # (キー, 値)のビューをタプルに変換

C:>python xxx.py
キー:(‘red’, ‘green’, ‘blue’)
値 :(‘赤’, ‘緑’, ‘青’)
要素:((‘red’, ‘赤’), (‘green’, ‘緑’), (‘blue’, ‘青’))

# 辞書から取り出したビューをもとに整数型インデックスでアクセス

item = list({'red': '赤', 'green': '緑', 'blue': '青'}.items())

print(f'item[0]    = {item[0]}')
print(f'item[1]    = {item[1]}')
print(f'item[2]    = {item[2]}')

print(f'item[0][0] = {item[0][0]}')
print(f'item[0][1] = {item[0][1]}')
print(f'item[1][0] = {item[1][0]}')
print(f'item[1][1] = {item[1][1]}')
print(f'item[2][0] = {item[2][0]}')
print(f'item[2][1] = {item[2][1]}')

C:>python xxx.py
item[0] = (‘red’, ‘赤’)
item[1] = (‘green’, ‘緑’)
item[2] = (‘blue’, ‘青’)
item[0][0] = red
item[0][1] = 赤
item[1][0] = green
item[1][1] = 緑
item[2][0] = blue
item[2][1] = 青

# 辞書から取り出したビューをもとに走査

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}

# keys()で取り出したビューをもとに走査
for key in rgb.keys():
    print(key)

# values()で取り出したビューをもとに走査
for value in rgb.values():
    print(value)

# itmes()で取り出したビューをもとに走査
for item in rgb.items():
    print(item)

C:>python xxx.py
red
green
blue



(‘red’, ‘赤’)
(‘green’, ‘緑’)
(‘blue’, ‘青’)

# 辞書から取り出したビューをもとに走査(items()からキーと値を別々に取り出す)

rgb = {'red': '赤', 'green': '緑', 'blue': '青'}

# keys()で取り出したビューをもとに走査
for key in rgb.keys():
    print(key)

# values()で取り出したビューをもとに走査
for value in rgb.values():
    print(value)

# itmes()で取り出したビューをもとに走査
for key, value in rgb.items():
    print(key, value)

C:>python xxx.py
red
green
blue



red 赤
green 緑
blue 青

# 文字列に含まれる文字の出現回数を辞書に格納(その1)

txt = input('文字列:')

count = {}
for ch in txt:
    if ch not in count:
        count[ch] = 1   # 辞書に挿入
    else:
        count[ch] += 1  # 要素の値を更新

print(f'分布={count}')

C:>python xxx.py
文字列:abc
分布={‘a’: 1, ‘b’: 1, ‘c’: 1}

# 文字列に含まれる文字の出現回数を辞書に格納(その2:辞書内包表記)

txt = input('文字列:')

count = {ch: txt.count(ch) for ch in txt}

print(f'分布={count}')

C:>python xxx.py
文字列:1qaz2wsx
分布={‘1’: 1, ‘q’: 1, ‘a’: 1, ‘z’: 1, ‘2’: 1, ‘w’: 1, ‘s’: 1, ‘x’: 1}

# 文字列に含まれる文字の出現回数を辞書に格納(その3:辞書内包表記【改良版】)

txt = input('文字列:')

count = { ch: txt.count(ch) for ch in set(txt)}

print("分布=", count)

C:>python xxx.py
文字列:1qaz
分布= {‘q’: 1, ‘a’: 1, ‘1’: 1, ‘z’: 1}

# 二つの文字列を集合化して集合演算を行う

set1 = set(input('文字列s1:'))
set2 = set(input('文字列s2:'))

print(f'set1:{set1}')
print(f'set2:{set2}')
print()
print(f'set1 == set2:{set1 == set2}')
print(f'set1 != set2:{set1 != set2}')
print(f'set1 <  set2:{set1 <  set2}')
print(f'set1 <= set2:{set1 <= set2}')
print(f'set1 >  set2:{set1 >  set2}')
print(f'set1 >= set2:{set1 >= set2}')
print()
print(f'set1 | set2:{set1 | set2}')
print(f'set1 & set2:{set1 & set2}')
print(f'set1 - set2:{set1 - set2}')
print(f'set1 ^ set2:{set1 ^ set2}')

C:>python xxx.py
文字列s1:abc
文字列s2:xyz
set1:{‘a’, ‘c’, ‘b’}
set2:{‘z’, ‘x’, ‘y’}

set1 == set2:False
set1 != set2:True
set1 < set2:False set1 <= set2:False set1 > set2:False
set1 >= set2:False

set1 | set2:{‘c’, ‘b’, ‘y’, ‘a’, ‘z’, ‘x’}
set1 & set2:set()
set1 – set2:{‘a’, ‘c’, ‘b’}
set1 ^ set2:{‘c’, ‘y’, ‘z’, ‘b’, ‘a’, ‘x’}

# 集合の生成

set01 = {1}                     # {1}
set02 = {1, 2, 3}               # {1, 2, 3}
set03 = {1, 2, 3,}              # {1, 2, 3}
set04 = {'A', 'B', 'C'}         # {'A', 'B', 'C'}

set05 = set()               # set()             空集合
set06 = set('ABC')          # {'A', 'B', 'C'}   文字列の個々の文字から生成
set07 = set([1, 2, 3])      # {1, 2, 3}         リストから生成
set08 = set([1, 2, 3, 2])   # {1, 2, 3}         リストから生成
set09 = set((1, 2, 3))      # {1, 2, 3}         タプルから生成

print('set01 =', set01)
print('set02 =', set02)
print('set03 =', set03)
print('set04 =', set04)
print('set05 =', set05)
print('set06 =', set06)
print('set07 =', set07)
print('set08 =', set08)
print('set09 =', set09)

C:>python xxx.py
set01 = {1}
set02 = {1, 2, 3}
set03 = {1, 2, 3}
set04 = {‘B’, ‘C’, ‘A’}
set05 = set()
set06 = {‘B’, ‘C’, ‘A’}
set07 = {1, 2, 3}
set08 = {1, 2, 3}
set09 = {1, 2, 3}

# タプルの生成

tuple01 = ()                    # ()
tuple02 = 1,                    # (1)
tuple03 = (1,)                  # (1)
tuple04 = 1, 2, 3               # (1, 2, 3)
tuple05 = 1, 2, 3,              # (1, 2, 3)
tuple06 = (1, 2, 3)             # (1, 2, 3)
tuple07 = (1, 2, 3, )           # (1, 2, 3)
tuple08 = 'A', 'B', 'C',        # ('A', 'B', 'C')

tuple09 = tuple()           # ()              空タプル
tuple10 = tuple('ABC')      # ('A', 'B', 'C') 文字列の個々の文字から生成
tuple11 = tuple([1, 2, 3])  # (1, 2, 3)       リストから生成
tuple12 = tuple({1, 2, 3})  # (1, 2, 3)       集合から生成

tuple13 = tuple(range(7))           # (0, 1, 2, 3, 4, 5, 6)
tuple14 = tuple(range(3, 8))        # (3, 4, 5, 6, 7)
tuple15 = tuple(range(3, 13, 2))    # (3, 5, 7, 9, 11)
tuple16 = divmod(13, 3)             # (4, 1)  4あまり1

print('tupe01 =', tuple01)
print('tupe02 =', tuple02)
print('tupe03 =', tuple03)
print('tupe04 =', tuple04)
print('tupe05 =', tuple05)
print('tupe06 =', tuple06)
print('tupe07 =', tuple07)
print('tupe08 =', tuple08)
print('tupe09 =', tuple09)
print('tupe10 =', tuple10)
print('tupe11 =', tuple11)
print('tupe12 =', tuple12)
print('tupe13 =', tuple13)
print('tupe14 =', tuple14)
print('tupe15 =', tuple15)
print('tupe16 =', tuple16)

C:>python xxx.py
tupe01 = ()
tupe02 = (1,)
tupe03 = (1,)
tupe04 = (1, 2, 3)
tupe05 = (1, 2, 3)
tupe06 = (1, 2, 3)
tupe07 = (1, 2, 3)
tupe08 = (‘A’, ‘B’, ‘C’)
tupe09 = ()
tupe10 = (‘A’, ‘B’, ‘C’)
tupe11 = (1, 2, 3)
tupe12 = (1, 2, 3)
tupe13 = (0, 1, 2, 3, 4, 5, 6)
tupe14 = (3, 4, 5, 6, 7)
tupe15 = (3, 5, 7, 9, 11)
tupe16 = (4, 1)

この記事は役に立ちましたか?

もし参考になりましたら、下記のボタンで教えてください。

関連記事

コメント

この記事へのコメントはありません。