python3

python3 で辞書からランダムに要素を選択する方法

投稿日:2020年12月15日 更新日:

items() で辞書から要素を取り出し、random.choice でランダムに要素を選択する。

import random

# 県庁所在地
mydict = {'宮城県':'仙台市','茨城県':'水戸市','島根県':'松江市','兵庫県':'神戸市','愛媛県':'松島市','沖縄県':'那覇市'}

# print(mydict)
first, second = random.choice(list(mydict.items()))
print('選択結果: '+first+' '+second)

結果

選択結果: 島根県 松江市
[商品価格に関しましては、リンクが作成された時点と現時点で情報が変更されている場合がございます。]

キングダム 1【電子書籍】[ 原泰久 ]
価格:564円(税別、送料別)(2020/12/24時点)

楽天で購入

-python3
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

matplotlib で、グラフの線の幅を変更する方法

lw で、線幅を数字で指定すればよい。 例 from matplotlib import pyplot as plt data_x = [25,26,27] data_y = [39, …

no image

python3 で切り捨て割り算(除算)

python3 で整数の割り算をして、商(の整数部)を表示するには // 演算子を使う。余りが発生した場合、商は切り捨てた整数部となる。 例 n = 201 print(str(n//2)) 結果 1 …

no image

python3 で、すべて小文字かどうかを判定する方法

islower() 関数を使う。 例 print(‘abcde’.islower()) print(‘abcDe’.islower()) 結果 True False

no image

matplotlib で、ヒストグラムを作成する方法

ヒストグラムを描くには、data_hist を使う。 ヒストグラムの縦棒の数は bins で指定する。 例 from matplotlib import pyplot as plt data_hist …

no image

python3 で辞書(dictionary)を削除する

clear() することによって、辞書が存在した状態のまま、キーと値をすべて削除することができる。 例 dict1 = {“名前”:”太郎”, “年齢”: 20, “住所”: “東京都千代田区大手町1 …