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

gnuplot で、グラフの形を正方形にする方法

set size square または、その省略形で set size sq というコマンドを使えば正方形の中にグラフを描くことができる。 例 set size square plot cos(x) …

no image

matplotlib で、凡例を表示する方法

データに label を関連付け、plt.legend() で凡例を表示する。 例 from matplotlib import pyplot as plt data_x = [25,26,2 …

no image

matplotlib で、線の種類を変更する方法

「linestyle = 」として、線の種類を指定することができる設定の詳細は、次のリンクを参照。 https://matplotlib.org/stable/gallery/lines_bars_a …

no image

matplotlib で、軸に垂直・平行な線を書く方法

axhline, axvline を使ってx,y軸に平行な線を描くことができる。 https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot …

no image

python でリストに、コロン演算子2つ(::)を使う

リストのコロンで指定できるパラメータには、「start, end, step」という意味がある。 以下の例では、:: 5 とした場合には、5 をステップとして、次に進んでいく。 ::-5 とした場合に …