Python ရှိ dictionary ၏ index-element အတွဲများ
Dictionary ၏ index များနှင့် element များကို tuple
ပုံစံဖြင့် ရရှိရန် enumerate function ကို
အသုံးပြုသင့်သည်။
ဥပမာ
ကျွန်ုပ်တို့တွင် dct dictionary ရှိသည်ဆိုပါစို့:
dct = {
'a': 1,
'b': 2,
'c': 3
}
၎င်း၏ key အားလုံးကို index များနှင့်အတူ ထုတ်ပြကြည့်ရအောင်:
for item in enumerate(dct):
print(item)
ကုဒ်ကို run ပြီးနောက် tuple များထွက်လာမည်၊ ၎င်းတွင် ပထမဆုံး index နှင့် နောက်မှ key တစ်ခုစီပါဝင်သည်:
(0, 'a')
(1, 'b')
(2, 'c')
ဥပမာ
Tuple ကို variable နှစ်ခုအဖြစ် unpack လုပ်နိုင်သည်:
for key, index in enumerate(dct):
print(key, index)
ကုဒ် run ပြီးနောက် ရလဒ်:
'a' 0
'b' 1
'c' 2
လက်တွေ့လေ့ကျင့်ခန်းများ
အောက်ပါ dictionary ကိုပေးထားသည်:
tst = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5
}
၎င်း၏ index များနှင့် key များကို tuple ပုံစံဖြင့် console တွင် ထုတ်ပြပါ။
အောက်ပါ dictionary ကိုပေးထားသည်:
tst = {
'1': 11,
'2': 12,
'3': 13,
'4': 14
}
၎င်း၏ index များနှင့် key များကို console တွင် ထုတ်ပြပါ။
အောက်ပါ dictionary ကိုပေးထားသည်:
tst = {
'x': 10,
'y': 20,
'z': 30
}
၎င်း၏ key များနှင့် index များကို console တွင် ထုတ်ပြပါ။