Python dictionaries มี keys และ values ถ้าเรามี dictionary สองตัวขึ้นไปที่ต้องการรวมเป็น nested dictionary เราสามารถใช้วิธีด้านล่างได้ ที่นี่ dictionary ถูกให้มาพร้อมกับ keys ใหม่ที่จะกลายเป็น key ใน nested dictionary
การกำหนด keys
ในวิธีนี้เราจะสร้าง dictionary ใหม่ว่าง แล้วกำหนด dictionary ที่ให้มาให้กับ key ใหม่แต่ละตัว dictionary ที่ได้จะเป็น nested dictionary พร้อมกับ keys ที่กำหนด
ตัวอย่าง
dictA = {'Sun': 1, 'Mon': 2}
dictB = {'Tue': 3, 'Sun': 5}
# Given Dictionaries
print("DictA : ", dictA)
print("DictB: ", dictB)
# Using key access and dict()
res = dict()
res['Nested_dict_1'] = dictA
res['Nested_dict_2'] = dictB
# printing result
print("Nested Dictionary: \n", res)
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
DictA : {'Sun': 1, 'Mon': 2}
DictB: {'Tue': 3, 'Sun': 5}
Nested Dictionary: {'Nested_dict_1': {'Sun': 1, 'Mon': 2}, 'Nested_dict_2': {'Tue': 3, 'Sun': 5}}
การใช้ zip
ฟังก์ชัน zip สามารถแปลง keys และ dictionaries เป็น tuple ได้ จากนั้นเราใช้ฟังก์ชัน dict เพื่อได้ผลลัพธ์สุดท้ายซึ่งเป็น dictionary ที่มี keys ใหม่และ dictionary ต้นฉบับ
ตัวอย่าง
dictA = {'Sun': 1, 'Mon': 2}
dictB = {'Tue': 3, 'Sun': 5}
# Given Dictionaries
print("DictA : ", dictA)
print("DictB: ", dictB)
# Using zip
dict_keys = ['Nested_dict_1', 'Nested_dict_2']
all_dicts = [dictA, dictB]
res = dict(zip(dict_keys, all_dicts))
# printing result
print("Nested Dictionary: \n", res)
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
DictA : {'Sun': 1, 'Mon': 2}
DictB: {'Tue': 3, 'Sun': 5}
Nested Dictionary: {'Nested_dict_1': {'Sun': 1, 'Mon': 2}, 'Nested_dict_2': {'Tue': 3, 'Sun': 5}}