python - Comment puis-je ajouter de nouvelles clés à un dictionnaire

Mots clés : pythondictionarylookuppython

meilleur 5 Réponses python - Comment puis-je ajouter de nouvelles clés à un dictionnaire

vote vote

97

d = {'key': 'value'} print(d)  # {'key': 'value'}  d['mynewkey'] = 'mynewvalue'  print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'} 
vote vote

80

>>> x = {1:2} >>> print(x) {1: 2}  >>> d = {3:4, 5:6, 7:8} >>> x.update(d) >>> print(x) {1: 2, 3: 4, 5: 6, 7: 8} 
vote vote

76

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' 
data |= {'c':3,'d':4} 
data3 = {} data3.update(data)  # Modifies data3, not data data3.update(data2)  # Modifies data3, not data2 
data = {**data1, **data2, **data3} 
data = data1 | {'c':3,'d':4} 
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)) 
vote vote

70

my_dict = {} 
my_dict['new key'] = 'new value' 
{'new key': 'new value'} 
my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'}) 
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'} 
my_dict.update(foo='bar', foo2='baz') 
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value',   'foo': 'bar', 'foo2': 'baz'} 
>>> 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 
vote vote

60

dictionary[key] = value 

Questions similaires