LoginSignup
0
1

【Python】辞書ネスト取得方法

Last updated at Posted at 2023-08-19

【Python】辞書型のネストから値を取得する方法

辞書の値に、辞書を用いることが出来ます。

{1:{'x':0}}

キーが「'x'」、値が「0」(内側の辞書)
キーが「1」、値が「{'x':0}」(外側の辞書)

辞書のネストから値を取得する2種類の方法

a = {1:{'x':100}}

# 変数に代入させて、アクセスする方法
a1 = a[1]
print(a1['x'])

# 変数使わずに一発で、アクセスする方法
print(a[1]['x'])
実行結果
100
100

書いてみた。

order = {
    'cake':{
        1:'chocolate', 
        2:'strawberry', 
        3:'fruits'}, 
    'drink':{
        1:'milk', 
        2:'coffee', 
        3:'tea'
     }
}

print(order['cake'][2])
print(order['drink'][3])
実行結果
strawberry
tea

こんな感じです。
orderにデータを代入する。
print(データを代入してあるorderを書く。)
そしてorderの中の、キーを[]に書いていきます。
その指示に従って、print関数を使って値を抽出していきます。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1