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

python3 で整数の割り算、商と余りを求める方法

floor divisionを使う。 例 a = 15 // 7 b = 15 % 7 print(a) print(b) 結果 2 1

no image

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

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

no image

matplotlib でグラフ表示ウィンドウの画面上の位置を自由に設定する方法

matplotlib.use(‘TkAgg’) としておき、 get_current_fig_manager().window.wm_geometry(“+20+50”) として、(+20+50)のと …

no image

matplotlib で2種類のcsvファイルをプロットする方法

data1.csv と、data2.csv の2つのファイルを散布図としてプロットするには次のようにする。 例 import numpy as np from matplotlib import py …

no image

matplotlib でcsv ファイルを読み込むとき、最初の行をスキップする方法

numpy の loadtxt で読み込む行を省略したい場合 スキップしたい行を # 等の記号でコメントアウトして、 loadtxt の comments = ‘#’ とすると …