파이썬 딕셔너리를 생성한 후에 키를 추가할 수 있나요? .add()` 메서드가 없는 것 같습니다.
d = {'key':'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'mynewkey': 'mynewvalue', 'key': 'value'}
I feel like 대한 정보를 통합 파이썬 사전:
data = {}
# OR
data = dict()
사전 만드는 초기 값을 # #
data = {'a':1,'b':2,'c':3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1),('b',2),('c',3))}
data['a']=1 # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a':1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)
data.update({'c':3,'d':4}) # Updates 'c' and adds 'd'
data3 = {}
data3.update(data) # Modifies data3, not data
data3.update(data2) # Modifies data3, not data2
del data[key] # Removes specific element in a dictionary
data.pop(key) # Removes the key & returns the value
data.clear() # Clears entire dictionary
key in data
for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys
data = dict(zip(list_with_keys, list_with_values))
data = {**data1, **data2, **data3}
Feel free to 추가!
>. # " 키를 추가할 수 있다, 파이썬 사전 이후 생성되는가? # 39, t () 이 있는 method." 지아다 doesn& 것으로 보인다.
예, 정보기술 (it) 이 구현하는 것이 없는 메서드입니다 확장하지만 don& # 39, 바로 사용할 수 없다.
얼마나, 어떻게 보여줄 수 없는 빈 딕트 let& 사용하며, # 39, s {} ',' 만들 수 있는 ipv6-literal. 딕트:
my_dict = {}
이 한 번의 새로운 업데이트하려면 딕트 키와 값을 사용할 수 있습니다. [이 아래 첨자 표기법 (http://otl. 매핑이라는 여기서요)] [1] 제공하는 항목설명프로세서 할당에서는:
my_dict['new key'] = 'new value'
'my_dict' 는 현재:
{'new key': 'new value'}
또한 여러 개의 값을 딕트 업데이트하십시오 아니라 효율적으로 사용하여 ['이' 업데이트 방법] [2]. 우리가 만들 수 있기 때문에 불필요하게 추가 '우리' 딕트 딕트 바란다 'here' 이미 만들어져 came from 또는 다른 용도로 사용되었다.
my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})
'my_dict' 는 현재:
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}
다른 효율적으로 수행할 수 있는 방법이 있지만, 키워드 인수만 업데이트하십시오 함께 있기 때문에 정당한 파이썬 나치도요 전날에약혼자에게 can& # 39, 이름 없는 공백 또는 특수 심볼이나 시작합니다. 고려해보십시오 더 잘 만들 수 있는 방법이 있지만, 많은 숫자로 이 키, 그리고 여기 확실히 딕트 대한 추가 피해야 불필요한 '딕트':
my_dict.update(foo='bar', foo2='baz')
'와' my_dict 이제.
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value',
'foo': 'bar', 'foo2': 'baz'}
이제 우리는 파이썬 덮여 있는 딕트 업데이트하더라도 '3'.
>>> d = {}
>>> d.__setitem__('foo', 'bar')
>>> d
{'foo': 'bar'}
>>> def f():
... d = {}
... for i in xrange(100):
... d['foo'] = i
...
>>> def g():
... d = {}
... for i in xrange(100):
... d.__setitem__('foo', i)
...
>>> import timeit
>>> number = 100
>>> min(timeit.repeat(f, number=number))
0.0020880699157714844
>>> min(timeit.repeat(g, number=number))
0.005071878433227539
그래서 우리가 지켜보리니 이 표기법을 사용하여 setitem 실제로 사용하는 것보다 훨씬 빨리 '아래'. 수행하는 파이썬 언어로 사용하는 것, 즉, 그 계산 방식은 보통 가독성을 높이고 보다 효율적으로 사용할 수 있도록 하기 위한 것입니다.
[1]: https://docs.python.org/2/reference/datamodel.html # 계층 표준 유형 [2]: https://docs.python.org/2/library/stdtypes.html # 딕트.업다이트
내 사전에 추가할 경우 사전 할 수 있어 이렇게.
예: 새로운 엔트리급에서 추가하기에서는 너회의 사전 &. 사전 서브노드
dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
print (dictionary)
{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}
dictionary["dictionary_within_a_dictionary"] = {}
함목과 추가하기 전에.
[핵심] = value 구문은 영업사원이에요 정통 신앙이니라 키보드의 키를 브래킷에서 누락되었습니다. 광장 ', 그럴 수도 있죠.
d.__setitem__(key, value)
사실, '정의' 와 '어떻게' 방법인 getitem setitem İç 수준의 지원 광장 브래킷에서 구문을 만들 수 있습니다. Https://python.developpez.com/cours/DiveIntoPython/php/endiveintopython/object_oriented_framework/special_class_methods.php 참조
한 개를 만들 수 있습니다.
class myDict(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
## example
myd = myDict()
myd.add('apples',6)
myd.add('bananas',3)
print(myd)
보기입니다:
>>>
{'apples': 6, 'bananas': 3}
널리 알려진 이 질문 메서드을 사전 'a' 와 'b' 충족합니다 기능 결합.
다음은 더 간단한 방법 (테스트를 파이썬 3).
c = dict( a, **b ) ## see also https://stackoverflow.com/q/2255878
c = dict( list(a.items()) + list(b.items()) )
c = dict( i for d in [a,b] for i in d.items() )
, 단일 요소를 추가하거나 수정할 수 있는 'b' 사전 하나만 요소에 포함될 예정이라고 말했다.
c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'
이 같습니다.
def functional_dict_add( dictionary, key, value ):
temp = dictionary.copy()
temp[key] = value
return temp
c = functional_dict_add( a, 'd', 'dog' )
params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}
params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})
이후 이 두:
'a& # 39, & # 39 params)', ' {여전히 같음. 1 b& # 39, & # 39;;: 2) '
및
'new_params a& # 39, & # 39', ' {동일합니다. 1 b& # 39, & # 39;;: 2 c& # 39, & # 39;;: 3) '
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3
또는
params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params.update({'c': 3})
그래서 이 질문에 대한 대답, 여전히 많은 사람들이 잊고 행동이 한 때 ' ()' 라는 기묘하게, 그럼에도 불구하고 여전히 딕트.세데포트 풀코스
이
value = my_dict.setdefault(key, default)
기본적으로 그냥 이거.
try:
value = my_dict[key]
except KeyError: # key not found
value = my_dict[key] = default
예:
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> mydict.setdefault('d', 4)
4 # returns new value at mydict['d']
>>> print(mydict)
{'a':1, 'b':2, 'c':3, 'd':4} # a new key/value pair was indeed added
# but see what happens when trying it on an existing key...
>>> mydict.setdefault('a', 111)
1 # old value was returned
>>> print(mydict)
{'a':1, 'b':2, 'c':3, 'd':4} # existing key was ignored
import timeit
timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary.update({"aaa": 123123, "asd": 233})')
>> 0.49582505226135254
timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary["aaa"] = 123123; dictionary["asd"] = 233;')
>> 0.20782899856567383
그러나 추가, 예를 들어, 걱정하지않아 you&; d # 39 와 같은 새로운 key-value 페어 '업데이트 ()' 를 사용하는 것이 좋습니다 메서드입니다.
또한 Python& 지적하는 것이 도움이 될 것 같아요 # 39 의 '모음' 모듈에서는 많은 유용한 구성된 사전 서브클래스 및 래퍼 및 수정, 특히 사전 아니라 단순화할 수 있는 데이터 유형 [ '데포트디스' ] [2]:
>. 누락된 값을 함수를 호출하는 하위 딕트 공장 공급
이 때 유용합니다 항상 동일한 데이터 형식이나 구조에 있는 작업하는 사전을 이루어져 있으며, 예를 들어 a dictionary of 있습니다.
>>> from collections import defaultdict
>>> example = defaultdict(int)
>>> example['key'] += 1
>>> example['key']
defaultdict(<class 'int'>, {'key': 1})
아직 존재하지 않는 경우, '키' 를 데포트디스 color_name 초기 값으로 주어진 값 (emc 의 경우 '10') 를 사전 (루프 내부에 사용되는 경우가 많다). 따라서 이 작업은 두 가지 않습니다. it 및 , 는 새 키를 사전 (따라 문제), t 키 값을 color_name 경우 이는 아직 존재하지 않습니다. doesn& # 39 와 같은 표준 오류를 사전에 제기하면서 '+ =' 작업은 액세스하려는 doesn& 값을 # 39, 아직 존재하지 않는다.
>>> example = dict()
>>> example['key'] += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'key'
사용하지 않고 ',' 데포트디스 코드의 양을 새 요소를 추가하는 것 같은데, 그 같은 일이 훨씬 더 클 것이다.
"'
예 [# 39, & # 39 key&;] = 0 # 키 추가 및 초기 값을 딕트. 바뀌엇어요 될 수도 있습니다 예 [# 39, & # 39 key&;] 이는 엇회전식 구축 = 1 # + "'
'데포트디스' 등 복잡한 데이터 유형을 함께 사용할 수 있습니다 '목록' 와 '세트'.
>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(<class 'list'>, {'key': [1]})
자동으로 초기화 명단요 요소를 추가
[2]: https://docs.python.org/3/library/collections.html # 콜레스티론스데포트디스