IT/Programming

[Python] Dictionary의 값이 List 타입일 때 Append 메서드 용례

nofence 2024. 4. 9. 11:11

Dicionary의 특정 키에 대한 값이 List 타입일 때, List 타입에서 제공하는 Append 메서드를  활용하여 요소를 추가할 수 있다. 

>>> test_dict = {"a":[], "b":[]}

>>> test_dict["a"].append(10,20,30)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list.append() takes exactly one argument (3 given)

>>> test_dict["a"].append(10)
>>> test_dict["a"].append(20)
>>> test_dict["a"].append(30)

>>> test_dict
{'a': [10, 20, 30], 'b': []}

 

당연한 얘기지만, Dictionary의 값이 튜플 타입일 때는 Append 메서드는 사용할 수 없다.

>>> test_dict2 = {"a":(), "b":()}

>>> test_dict2["a"].append(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

 

 

* 참고

https://www.guru99.com/python-dictionary-append.html