【Python】Python - 巢狀Dictionaries。Python Nested Dictionaries.
【Python】Python - 巢狀Dictionaries。Python Nested Dictionaries.
一個dictionary內還可再包含多個dictionaries,這種稱為巢狀dictionaries。
範例
建立一個dictionary內含3個dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
上面輸出:
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
或是另外建立一個新的dictionary內含3個dictionaries:
範例
建立3個dictionaries,接著建立1個dictionary為容器去容納其他3個 dictionaries。
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
printf(myfamily)
上面輸出:
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
留言
張貼留言