-
[Python tutorial] 10. Data type - Dictionary코딩/Python 2022. 12. 21. 17:14728x90
Dictionaries
- key:value pairs
- ordered
- changeable
- do not allow duplicates
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 # any data types } print(thisdict) print(thisdict["brand"])
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
FordAccess Dictionary Items
x = thisdict["model"] print(x) # Mustang # get() x = thisdict.get("model") print(x) # Mustang # Get Keys: keys() x = thisdict.keys() # return list print(x) # dict_keys(['brand', 'model', 'year']) # Get Values: values() x = thisdict.values() print(x) # dict_values(['Ford', 'Mustang', 1964]) # Get Items: items() as tuples in a list x = thisdict.items() print(x) # dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Check if Key Exists: in
if "model" in thisdict: print("Yes, 'model' is one of the keys in the thisdict dictionary")
Change Dictionary Items
thisdict["year"] = 2018 # Update Dictionary: update() thisdict.update({"year": 2020}) # If the item does not exist, the item will be added. # Add Dictionary Items thisdict["color"] = "red"
Remove Dictionary Items
# pop() thisdict.pop("model") # popitem(): remove last item thisdict.popitem() # del: specified key name del thisdict["model"] del thisdict # delete the dictionary completely # clear() thisdict.clear() print(thisdict) # {}
Loop Dictionaries
keys
# for for x in thisdict: print(x) # return keys # keys for x in thisdict.keys(): print(x)
values
# index for x in thisdict: print(thisdict[x]) # return values # values() for x in thisdict.values(): print(x)
keys & values
# items(): keys & values for x, y in thisdict.items(): print(x, y)
brand Ford
model Mustang
year 1964Copy Dictionaries
# copy() mydict = thisdict.copy() # dict() mydict = dict(thisdict)
Nested Dictionaries
dictionary can contain dictionaries
# dictionary that contain three 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}}
child1 = { "name" : "Emil", "year" : 2004 } child2 = { "name" : "Tobias", "year" : 2007 } child3 = { "name" : "Linus", "year" : 2011 } myfamily = { "child1" : child1, "child2" : child2, "child3" : child3 } print(myfamily) {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
728x90'코딩 > Python' 카테고리의 다른 글
[Python tutorial] 12. Control flow, If...else (0) 2022.12.21 [Python tutorial] 11. Operators (0) 2022.12.21 [Python tutorial] 9. Data type - Sets (0) 2022.12.21 [Python tutorial] 8. Data type - Tuple (0) 2022.12.21 [Python tutorial] 7. Data type - List (0) 2022.12.21