Banyak dari Anda menghubungi saya untuk meminta sumber daya berharga untuk menyelesaikan wawancara Rekayasa Data berbasis Python. Di bawah ini saya membagikan 3 kursus sesuai permintaan yang sangat saya rekomendasikan
- Rekayasa Data Python Nanodegree→ Kursus Berkualitas Tinggi + Proyek Pengkodean Jika Anda Punya Waktu Untuk Berkomitmen. → Dapatkan DISKON 70% Melalui Link Ini
- LeetCode Dengan Python. 50 Pertanyaan Wawancara Coding Algoritma → Terbaik Untuk Putaran Coding Melibatkan Algoritma
- Masalah Coding tingkat lanjut Python (StrataScratch) → Platform terbaik yang saya temukan untuk menyiapkan wawancara pengkodean Python & SQL sejauh ini. Lebih baik dan lebih murah daripada LeetCode
Harap Anda akan menemukan mereka berguna juga. Sekarang nikmati artikelnya. D
pengantarKamus Python didefinisikan sebagai kumpulan nilai data, di mana item disimpan sebagai pasangan kunci-nilai. Untuk alasan ini, kamus juga dikenal sebagai array asosiatif
Jika Anda relatif baru di Python, atau Anda sedang mempersiapkan putaran pengkodean berikutnya, Anda mungkin menemukan sejumlah algoritme yang perlu berinteraksi dengan kamus.
Namun, tampaknya kamus terus membangkitkan minat tidak hanya di kalangan pemula, tetapi juga di kalangan pengembang yang lebih berpengalaman. Akibatnya, melihat pertanyaan Stack Overflow Python teratas sepanjang waktu, tampaknya tiga topik yang paling banyak dipilih adalah
- Bagaimana cara mengulang kamus menggunakan loop 'untuk'?
- Bagaimana cara memeriksa apakah kunci yang diberikan sudah ada di kamus?
- Bagaimana cara menambahkan kunci baru ke kamus?
Pada artikel ini, saya akan mencoba memberi Anda jawaban yang ringkas dan jelas untuk setiap pertanyaan ini. Ini akan menghindarkan Anda dari membaca lusinan komentar di web
Mari kita mulai dari atas. 👆👆🏽👆🏻
Bagaimana cara mengulang kamus menggunakan loop 'untuk'?Untuk menjawab pertanyaan ini, saya telah membuat kamus berisi data transaksi perbankan online tiruan
‘transaction_id’: 1000001,
‘source_country’: ‘United Kingdom’,
‘target_country’: ‘Italy’,
‘send_currency’: ‘GBP’,
‘send_amount’: 1000.00,
‘target_currency’: ‘EUR’,
‘fx_rate’: 1.1648674,
‘fee_pct’: 0.50,
‘platform’: ‘mobile’
}
Metode 1. Iterasi Menggunakan For Loop + Indexing
Cara termudah untuk beralih melalui kamus dengan Python, adalah dengan meletakkannya langsung di # METHOD 1 - Unsorted
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile4 loop. Python akan secara otomatis memperlakukan # METHOD 1 - Unsorted
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile5 sebagai kamus dan memungkinkan Anda untuk mengulang kuncinya
Kemudian, untuk juga mendapatkan akses ke nilai, Anda dapat meneruskan setiap kunci ke kamus menggunakan operator pengindeksan# METHOD 1 - Unsorted
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile6
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile_
Seperti yang Anda lihat, kunci tidak diurutkan berdasarkan abjad. Untuk mencapainya, Anda cukup meneruskan # METHOD 1 - Unsorted
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile5 ke metode # METHOD 1 - Unsorted
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile8
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 1000001
Metode 2. Iterasi Menggunakan. kunci( ) + Pengindeksan
Hasil yang sama dapat diperoleh dengan menggunakan metode # METHOD 1 - Unsorted
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile_9 yang mengembalikan objek Python termasuk kunci kamus
Ini sangat berguna ketika Anda hanya perlu mengulangi kunci kamus, tetapi juga dapat digunakan dalam kombinasi dengan operator pengindeksan untuk mengambil nilai
# METHOD 2for key in transaction_data.keys():
print(key, '-->', transaction_data[key])Output[3]:
transaction_id --> 1000001
source_country --> United Kingdom
target_country --> Italy
send_currency --> GBP
send_amount --> 1000.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> mobile_
Metode 3. Iterasi Menggunakan. item( )
Namun, cara yang paling "pythonic" dan elegan untuk beralih melalui kamus adalah dengan menggunakan metode # METHOD 1 - Sorted
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 10000010, yang mengembalikan tampilan item kamus sebagai tupel
dict_items([('transaction_id', 1000001),
('source_country', 'United Kingdom'),
('target_country', 'Italy'),
('send_currency', 'GBP'),
('send_amount', 1000.0),
('target_currency', 'EUR'),
('fx_rate', 1.1648674),
('fee_pct', 0.5),
('platform', 'mobile')])
Untuk mengulangi kunci dan nilai kamus # METHOD 1 - Unsorted
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile5, Anda hanya perlu 'membongkar' dua item yang disematkan di tuple seperti yang ditunjukkan di bawah ini
for k,v in transaction_data.items():
print(k,’>>’,v)Output[5]:
transaction_id >> 1000001
source_country >> United Kingdom
target_country >> Italy
send_currency >> GBP
send_amount >> 1000.0
target_currency >> EUR
fx_rate >> 1.1648674
fee_pct >> 0.5
platform >> mobile
Perhatikan bahwa k dan v hanyalah alias standar untuk 'kunci' dan 'nilai', tetapi Anda juga dapat memilih konvensi penamaan alternatif. Misalnya menggunakan a dan b mengarah ke output yang sama
print(a,’~’,b)Output[6]:
transaction_id ~ 1000001
source_country ~ United Kingdom
target_country ~ Italy
send_currency ~ GBP
send_amount ~ 1000.0
target_currency ~ EUR
fx_rate ~ 1.1648674
fee_pct ~ 0.5
platform ~ mobile
Ekstra - Iterasi Melalui Kamus Bersarang 🤓
Tetapi bagaimana jika Anda perlu mengulang melalui kamus bersarang seperti # METHOD 1 - Sorted
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 10000012 ?
‘transaction_1’:{
‘transaction_id’: 1000001,
‘source_country’: ‘United Kingdom’,
‘target_country’: ‘Italy’,
‘send_currency’: ‘GBP’,
‘send_amount’: 1000.00,
‘target_currency’: ‘EUR’,
‘fx_rate’: 1.1648674,
‘fee_pct’: 0.50,
‘platform’: ‘mobile’
},
‘transaction_2’:{
‘transaction_id’: 1000002,
‘source_country’: ‘United Kingdom’,
‘target_country’: ‘Germany’,
‘send_currency’: ‘GBP’,
‘send_amount’: 3320.00,
‘target_currency’: ‘EUR’,
‘fx_rate’: 1.1648674,
‘fee_pct’: 0.50,
‘platform’: ‘Web’
},
‘transaction_3’:{
‘transaction_id’: 1000003,
‘source_country’: ‘United Kingdom’,
‘target_country’: ‘Belgium’,
‘send_currency’: ‘GBP’,
‘send_amount’: 1250.00,
‘target_currency’: ‘EUR’,
‘fx_rate’: 1.1648674,
‘fee_pct’: 0.50,
‘platform’: ‘Web’
}
}
Untuk membongkar pasangan kunci-nilai milik setiap kamus bersarang, Anda dapat menggunakan loop berikut
#1. Selecting key-value pairs for all the transactionsfor k, v in transaction_data_n.items():if type(v) is dict:
for nk, nv in v.items():
print(nk,’ →’, nv)#nk and nv stand for nested key and nested valueOutput[7]:
transaction_id --> 1000001
source_country --> United Kingdom
target_country --> Italy
send_currency --> GBP
send_amount --> 1000.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> mobile
transaction_id --> 1000002
source_country --> United Kingdom
target_country --> Germany
send_currency --> GBP
send_amount --> 3320.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> Web
transaction_id --> 1000003
source_country --> United Kingdom
target_country --> Belgium
send_currency --> GBP
send_amount --> 1250.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> Web-----------------------------#2. Selecting key-value pairs for 'transaction_2 only'for k, v in transaction_data_n.items():
if type(v) is dict and k == 'transaction_2':
for sk, sv in v.items():
print(sk,'-->', sv)Output[8]:
transaction_id --> 1000002
source_country --> United Kingdom
target_country --> Germany
send_currency --> GBP
send_amount --> 3320.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> WebBagaimana cara memeriksa apakah kunci yang diberikan sudah ada dalam kamus?
Anda dapat memeriksa keanggotaan kamus Python menggunakan operator # METHOD 1 - Sorted
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 10000013
Secara khusus, katakanlah Anda ingin memeriksa apakah bidang # METHOD 1 - Sorted
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 10000014 tersedia sebagai kunci di # METHOD 1 - Unsorted
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile5. Dalam hal ini Anda bisa lari
True
Demikian pula, untuk memeriksa apakah nilai # METHOD 1 - Sorted
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 10000016 sudah ditetapkan ke kunci dalam kamus, Anda dapat menjalankan
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile_0
Namun, pemeriksaan di atas tidak akan langsung memberi tahu Anda jika # METHOD 1 - Sorted
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 10000016 adalah nilai yang ditetapkan ke kunci # METHOD 1 - Sorted
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 10000014 atau kunci # METHOD 1 - Sorted
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 10000019. Untuk mengonfirmasi itu, Anda dapat meneruskan tuple ke metode # METHOD 2
for key in transaction_data.keys():
print(key, '-->', transaction_data[key])Output[3]:
transaction_id --> 1000001
source_country --> United Kingdom
target_country --> Italy
send_currency --> GBP
send_amount --> 1000.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> mobile0
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile_1
Jika kamus # METHOD 1 - Unsorted
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile_5 menyertakan ratusan nilai, ini akan menjadi cara sempurna untuk memeriksa bahwa # METHOD 1 - Sorted
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 10000016 memang # METHOD 1 - Sorted
for key in sorted(transaction_data):
print(key, ‘:’, transaction_data[key])Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 10000014 untuk transaksi spesifik tersebut
Berguna. 😏😏😏
Terakhir, anggap saja, pada titik tertentu, Tim Analytics meminta Anda untuk menambahkan bidang # METHOD 2
for key in transaction_data.keys():
print(key, '-->', transaction_data[key])Output[3]:
transaction_id --> 1000001
source_country --> United Kingdom
target_country --> Italy
send_currency --> GBP
send_amount --> 1000.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> mobile4 dan # METHOD 2
for key in transaction_data.keys():
print(key, '-->', transaction_data[key])Output[3]:
transaction_id --> 1000001
source_country --> United Kingdom
target_country --> Italy
send_currency --> GBP
send_amount --> 1000.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> mobile5 ke data yang tersedia di kamus. Bagaimana Anda akan mencapai itu?
Ada dua metode utama
- Menggunakan tanda kurung siku # METHOD 1 - Unsorted
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile_6 notasi
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile_2
- Sebagai alternatif, Anda dapat menggunakan metode # METHOD 2
for key in transaction_data.keys():
print(key, '-->', transaction_data[key])Output[3]:
transaction_id --> 1000001
source_country --> United Kingdom
target_country --> Italy
send_currency --> GBP
send_amount --> 1000.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> mobile_7, tetapi ada sedikit lebih banyak pengetikan yang terlibat
for key in transaction_data:
print(key, ‘:’, transaction_data[key])Output[1]:
transaction_id : 1000001
source_country : United Kingdom
target_country : Italy
send_currency : GBP
send_amount : 1000.0
target_currency : EUR
fx_rate : 1.1648674
fee_pct : 0.5
platform : mobile3Kesimpulan
Dalam artikel ini, saya membagikan 3 metode untuk beralih melalui kamus Python dengan loop 'untuk' dan mengekstrak pasangan nilai kunci secara efisien. Namun, ketahuilah bahwa ada lebih banyak solusi 'pythonic' (i. e. pemahaman kamus)
Meskipun merupakan topik yang relatif mendasar, "bagaimana cara mengulangi kamus Python?", Adalah salah satu pertanyaan yang paling banyak dipilih yang pernah diajukan di Stack Overflow
Untuk alasan ini, saya juga menjawab dua pertanyaan Stack Overflow yang sangat populer lainnya tentang memeriksa keanggotaan dan menambahkan pasangan nilai kunci baru ke kamus Python
Harapan saya adalah Anda akan menggunakan artikel ini untuk mengklarifikasi semua keraguan Anda tentang kamus di tempat yang sama. Mempelajari kode itu menyenangkan dan akan mengubah hidup Anda selamanya, jadi teruslah belajar
Sebuah Catatan Untuk Pembaca Saya
Posting ini menyertakan tautan afiliasi di mana saya dapat membuat komisi kecil tanpa biaya tambahan untuk Anda, jika Anda melakukan pembelian