programing

Python에서 새 사전 만들기

javaba 2022. 11. 26. 21:38
반응형

Python에서 새 사전 만들기

나는 파이썬으로 사전을 만들고 싶다.그러나 내가 보는 모든 예는 사전의 목록 등입니다.

Python에서 빈 사전을 새로 만들려면 어떻게 해야 하나요?

불러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}

python 사전에 값을 추가합니다.

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]}

저는 아직 평판이 좋지 않아서 답변으로 공유합니다.

Doug Hellmann이 자신의 사이트를 이행했기 때문에 @David Whiton이 수락한 답변에 대한 코멘트에서 공유한 링크는 유효하지 않습니다(출처:https://doughellmann.com/posts/wordpress-to-hugo/)).

다음 링크에서는 "CPython 2.7에서 {} 대신 dict()를 사용하면 퍼포먼스에 미치는 영향"에 대해 설명합니다.https://doughellmann.com/posts/the-performance-impact-of-using-dict-instead-of-in-cpython-2-7-2/

언급URL : https://stackoverflow.com/questions/8424942/creating-a-new-dictionary-in-python

반응형