Programming

파이썬에서 새로운 받아쓰기

procodes 2020. 2. 20. 23:40
반응형

파이썬에서 새로운 받아쓰기


파이썬으로 사전을 만들고 싶습니다. 그러나 내가 보는 모든 예제는 목록에서 사전을 인스턴스화하는 것입니다. ..

파이썬에서 빈 사전을 새로 만들려면 어떻게합니까?


dict매개 변수없이 호출

new_dict = dict()

또는 간단히 쓰십시오

new_dict = {}

당신은 이것을 할 수 있습니다

x = {}
x['a'] = 1

사전 설정 사전을 작성하는 방법을 아는 것도 유용합니다.

cmap =  {'US':'USA','GB':'Great Britain'}

# Explicitly:
# -----------
def cxlate(country):
    try:
        ret = cmap[country]
    except KeyError:
        ret = '?'
    return ret

present = 'US' # this one is in the dict
missing = 'RU' # this one is not

print cxlate(present) # == USA
print cxlate(missing) # == ?

# or, much more simply as suggested below:

print cmap.get(present,'?') # == USA
print cmap.get(missing,'?') # == ?

# with country codes, you might prefer to return the original on failure:

print cmap.get(present,present) # == USA
print cmap.get(missing,missing) # == RU

>>> dict(a=2,b=4)
{'a': 2, 'b': 4}

파이썬 사전에 값을 추가합니다.


d = dict()

또는

d = {}

또는

import types
d = types.DictType.__new__(types.DictType, (), {})

dict를 만드는 두 가지 방법이 있습니다.

  1. my_dict = dict()

  2. my_dict = {}

그러나이 두 가지 옵션 중 읽기 가능 옵션 {}보다 효율적 dict()입니다. 여기를 확인하십시오


>>> dict.fromkeys(['a','b','c'],[1,2,3])


{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

참고 URL : https://stackoverflow.com/questions/8424942/creating-a-new-dict-in-python



반응형