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 で辞書(dictionary)の一部を del で削除する

辞書の一部を削除するには、del で消去したいキーを指定する。 例 dict1 = {“名前”:”太郎”, “年齢”: 20, “住所”: “東京都千代田区大手町1-1”} print(dict1) …

no image

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

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

no image

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

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

no image

matplotlib で、グラフのタイトルに上付き文字を入力する方法

数学記号などで、グラフのタイトルに上付きの文字を入力したい場合がある。 その場合は次のように書いて設定できる。 例 import numpy as np from matplotlib import …

no image

matplotlib で複数のグラフを並べて表示する方法

plot.subplots() でグラフの縦方向と横方向の数を指定する。 例 import numpy as np from matplotlib import pyplot as plt x1 = …