자료구조 : 딕셔너리

딕셔너리 (dictionary)

  • 딕셔너리
    value of key can't be changed
    value of key can't be duplicated in the same dictionary (if you do, the value of key can be overwritten of the new one.)

  • 딕셔너리 생성
    key values can't be duplicated,but value values can be duplicated.

    Ex.

    ```
    my_dic = {}
    my_dic = dict()
    my_dic = {'a':111, 'b':222, 'c':333, 'd':444}   
    ```

  • 데이터 조회
    - access with key

    Ex.

    ```
    pro_dic = { 
      'name' : 'DRAM',
      'capa' : '32g',
      'maker' : 'SK',
      'price' : 320000
    }
    print(pro_dic.get('name')) 	# get(key)
    print(pro_dic['name'])		# dict[key]
    ```
    By using 'in' function, you can check if the key value is in that dictionary

    Ex.

    ```
    print('maker' in pro_dic) 	# True
    print('price' in pro_dic)	# True
    print('ssn' in pro_dic)		# False
    ```

  • 값 추가
    - dict1.update(dict2) : insert dict2 at the end of the dict1

    Ex.

    ```
    pro_dic['ssn'] = 1234
    print(pro_dic)
    ####################################################
    add_info = {
    	'loc': '이천',
    	'pop': 33
    }
    pro_dic.update(add_info)
    print(pro_dic)
    ```

    ㄴ> 출력 값

    ```
    {'name': 'DRAM', 'capa': '32g', 'maker': 'SK', 'price': 320000, 'ssn': 1234}
    {'name': 'DRAM', 'capa': '32g', 'maker': 'SK', 'price': 320000, 'ssn': 1234, 'loc': '이천', 'pop': 33}
    ```

  • 값 수정

    Ex.

    ```
    pro_dic[price] = 230000
    print(pro_dic)
    ```

    ㄴ> 출력 값

    ```
    {'name': 'DRAM', 'capa': '32g', 'maker': 'SK', 'price': 230000, 'ssn': 1234, 'loc': '이천', 'pop': 33}
    ```

  • 데이터 삭제
    - del dict[key1] : delete a key-value element that has a key value of key1
    - pop(key1) : delete a key-value element that has a key value of key1
    - clear() : delete all elements in that dictionary

    Ex.

    ```
    del pro_dic['loc']
    pro_dic.pop('pop')
    pro_dic.clear()
    ```

  • 딕셔너리 함수 etc ... (keys, values, items, ...)
    - keys() : return all key values in that dictionary (return type : dict_keys)
    - values() : return all value values in that dictionary (return type : dict_values)
    - items() : return tuple(key, value) in that dictionary (return type : dict_items)

    Ex.

    ```
    my_dic = {
    	'name': 'James',
    	'age': 34,
    	'address': 'Texas',
    	'phone': '123456'
    }
    my_keys = my_dic.keys()
    my_keys = list(my_keys)
    print(my_keys)
    #
    my_values = my_dic.values()
    my_values = list(my_values)
    print(my_values)
    #
    my_items = my_dic.items()
    my_items = list(my_items)
    print(my_items)
    ```

    ㄴ> 출력값

    ```
    ['name', 'age', 'address', 'phone']
    ['James', 34, 'Texas', '123456']
    [('name', 'James'), ('age', 34), ('address', 'Texas'), ('phone', '123456')]
    ```

좋은 웹페이지 즐겨찾기