- How can I add new keys to a dictionary?
- Creating an empty dictionary
- Creating a dictionary with initial values
- Inserting/Updating a single value
- Inserting/Updating multiple values
- Python 3.9+:
- Creating a merged dictionary without modifying originals
- Python 3.5+:
- Python 3.9+:
- Deleting items in dictionary
- Check if a key is already in dictionary
- Iterate through pairs in a dictionary
- Create a dictionary from two lists
- «Is it possible to add a key to a Python dictionary after it has been created? It doesn’t seem to have an .add() method.»
- Best Practice 1: Subscript notation
- Best Practice 2: The update method — 2 ways
- Magic method, __setitem__ , and why it should be avoided
- Adding new keys without updating the existing dict
- Python >= 3.5
- Python < 3.5
How can I add new keys to a dictionary?
If the key doesn’t exist, it’s added and points to that value. If it exists, the current value it points to is overwritten.
@hegash the dPython dictionary добавить пару=val syntax as it is shorter and can handle any object as key (as long it is hashable), and only sets one value, whereas the .update(key1=val1, key2=val2) is nicer if you want to set multiple values at the same time, as long as the keys are strings (since kwargs are converted to strings). dict.update can also take another dictionary, but I personally prefer not to explicitly create a new dictionary in order to update another one.
Based on If it exists, the current value it points to is overwritten. how can i make it elegantly check if the key i m trying to add info on, already exists and then raise exception?
@Selfcontrol7 append is not a dict’s method, it’s a method for lists, it adds a value at the end of the list.
I feel like consolidating info about Python dictionaries:
Creating an empty dictionary
Creating a dictionary with initial values
data = # OR data = dict(a=1, b=2, c=3) # OR data =
Inserting/Updating a single value
data['a'] = 1 # Updates if 'a' exists, else adds 'a' # OR data.update() # OR data.update(dict(a=1)) # OR data.update(a=1)
Inserting/Updating multiple values
data.update() # Updates 'c' and adds 'd'
Python 3.9+:
The update operator |= now works for dictionaries:
Creating a merged dictionary without modifying originals
data3 = <> data3.update(data) # Modifies data3, not data data3.update(data2) # Modifies data3, not data2
Python 3.5+:
This uses a new feature called dictionary unpacking.
Python 3.9+:
The merge operator | now works for dictionaries:
Deleting items in dictionary
del dataPython dictionary добавить пару # Removes specific element in a dictionary data.pop(key) # Removes the key & returns the value data.clear() # Clears entire dictionary
Check if a key is already in dictionary
Iterate through pairs in a dictionary
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
Create a dictionary from two lists
data = dict(zip(list_with_keys, list_with_values))
The «OR» operator | in 3.9 appears to solve my issue with python dicts not having any builder pattern.
Would be good to mention for the various options of «update one entry», that the ones using «update» have the overhead of creating a temporary dictionary.
To add multiple keys simultaneously, use dict.update() :
>>> x = >>> print(x) >>> d = >>> x.update(d) >>> print(x)
For adding a single key, the accepted answer has less computational overhead.
«Is it possible to add a key to a Python dictionary after it has been created? It doesn’t seem to have an .add() method.»
Yes it is possible, and it does have a method that implements this, but you don’t want to use it directly.
To demonstrate how and how not to use it, let’s create an empty dict with the dict literal, <> :
Best Practice 1: Subscript notation
To update this dict with a single new key and value, you can use the subscript notation (see Mappings here) that provides for item assignment:
my_dict['new key'] = 'new value'
Best Practice 2: The update method — 2 ways
We can also update the dict with multiple values efficiently as well using the update method. We may be unnecessarily creating an extra dict here, so we hope our dict has already been created and came from or was used for another purpose:
Another efficient way of doing this with the update method is with keyword arguments, but since they have to be legitimate python words, you can’t have spaces or special symbols or start the name with a number, but many consider this a more readable way to create keys for a dict, and here we certainly avoid creating an extra unnecessary dict :
my_dict.update(foo='bar', foo2='baz')
So now we have covered three Pythonic ways of updating a dict .
Magic method, __setitem__ , and why it should be avoided
There’s another way of updating a dict that you shouldn’t use, which uses the __setitem__ method. Here’s an example of how one might use the __setitem__ method to add a key-value pair to a dict , and a demonstration of the poor performance of using it:
>>> d = <> >>> d.__setitem__('foo', 'bar') >>> d >>> 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
So we see that using the subscript notation is actually much faster than using __setitem__ . Doing the Pythonic thing, that is, using the language in the way it was intended to be used, usually is both more readable and computationally efficient.
The difference is rather less marked in 2020 (on my machine, 1.35 ms subscripting vs 2ms for d.__setitem__ ), though the conclusion (and especially the last sentence) remains sound. Hoisting the method name lookup out of the loop reduced time to about 1.65 ms; the remaining difference is likely largely due to unavoidable Python call mechanism overhead.
If you want to add a dictionary within a dictionary you can do it this way.
Example: Add a new entry to your dictionary & sub dictionary
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"] = print (dictionary)
NOTE: Python requires that you first add a sub
dictionary["dictionary_within_a_dictionary"] = <>
The conventional syntax is dPython dictionary добавить пару = value , but if your keyboard is missing the square bracket keys you could also do:
In fact, defining __getitem__ and __setitem__ methods is how you can make your own class support the square bracket syntax. See Dive Into Python, Classes That Act Like Dictionaries.
class myDict(dict): def __init__(self): self = dict() def add(self, key, value): selfPython dictionary добавить пару = value ## example myd = myDict() myd.add('apples',6) myd.add('bananas',3) print(myd)
This popular question addresses functional methods of merging dictionaries a and b .
Here are some of the more straightforward methods (tested in Python 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() )
Note: The first method above only works if the keys in b are strings.
To add or modify a single element, the b dictionary would contain only that one element.
c = dict( a, ** ) ## returns a dictionary based on 'a'
def functional_dict_add( dictionary, key, value ): temp = dictionary.copy() tempPython dictionary добавить пару = value return temp c = functional_dict_add( a, 'd', 'dog' )
Let’s pretend you want to live in the immutable world and do not want to modify the original but want to create a new dict that is the result of adding a new key to the original.
In Python 3.5+ you can do:
The Python 2 equivalent is:
params = new_params = dict(params, **)
There will be times when you don’t want to modify the original (you only want the result of adding to the original). I find this a refreshing alternative to the following:
params = new_params = params.copy() new_params['c'] = 3
params = new_params = params.copy() new_params.update()
There is also the strangely named, oddly behaved, and yet still handy dict.setdefault() .
value = my_dict.setdefault(key, default)
try: value = my_dictPython dictionary добавить пару except KeyError: # key not found value = my_dictPython dictionary добавить пару = default
>>> mydict = >>> mydict.setdefault('d', 4) 4 # returns new value at mydict['d'] >>> print(mydict) # 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) # existing key was ignored
This question has already been answered ad nauseam, but since my (now deleted) comment gained a lot of traction, here it is as an answer:
Adding new keys without updating the existing dict
If you are here trying to figure out how to add a key and return a new dictionary (without modifying the existing one), you can do this using the techniques below
Python >= 3.5
Python < 3.5
new_dict = dict(mydict, new_key=new_val)
Note that with this approach, your key will need to follow the rules of valid identifier names in Python.
If you’re not joining two dictionaries, but adding new key-value pairs to a dictionary, then using the subscript notation seems like the best way.
import timeit timeit.timeit('dictionary = ; dictionary.update()') >> 0.49582505226135254 timeit.timeit('dictionary = ; dictionary["aaa"] = 123123; dictionary["asd"] = 233;') >> 0.20782899856567383
However, if you’d like to add, for example, thousands of new key-value pairs, you should consider using the update() method.
Here’s another way that I didn’t see here:
>>> foo = dict(a=1,b=2) >>> foo >>> goo = dict(c=3,**foo) >>> goo
You can use the dictionary constructor and implicit expansion to reconstruct a dictionary. Moreover, interestingly, this method can be used to control the positional order during dictionary construction (post Python 3.6). In fact, insertion order is guaranteed for Python 3.7 and above!
>>> foo = dict(a=1,b=2,c=3,d=4) >>> new_dict = >>> new_dict >>> new_dict.update(newvalue=99) >>> new_dict >>> new_dict.update() >>> new_dict >>>
The above is using dictionary comprehension.
First to check whether the key already exists:
Then you can add the new key and value.
Add a dictionary (key,value) class.
class myDict(dict): def __init__(self): self = dict() def add(self, key, value): #selfPython dictionary добавить пару = value # add new key and value overwriting any exiting same key if self.get(key)!=None: print('key', key, 'already used') # report if key already used self.setdefault(key, value) # if key exit do nothing ## example myd = myDict() name = "fred" myd.add('apples',6) print('\n', myd) myd.add('bananas',3) print('\n', myd) myd.add('jack', 7) print('\n', myd) myd.add(name, myd) print('\n', myd) myd.add('apples', 23) print('\n', myd) myd.add(name, 2) print(myd)
I think it would also be useful to point out Python’s collections module that consists of many useful dictionary subclasses and wrappers that simplify the addition and modification of data types in a dictionary, specifically defaultdict :
dict subclass that calls a factory function to supply missing values
This is particularly useful if you are working with dictionaries that always consist of the same data types or structures, for example a dictionary of lists.
>>> from collections import defaultdict >>> example = defaultdict(int) >>> example['key'] += 1 >>> example['key'] defaultdict(, )
If the key does not yet exist, defaultdict assigns the value given (in our case 10 ) as the initial value to the dictionary (often used inside loops). This operation therefore does two things: it adds a new key to a dictionary (as per question), and assigns the value if the key doesn’t yet exist. With the standard dictionary, this would have raised an error as the += operation is trying to access a value that doesn’t yet exist:
>>> example = dict() >>> example['key'] += 1 Traceback (most recent call last): File "", line 1, in KeyError: 'key'
Without the use of defaultdict , the amount of code to add a new element would be much greater and perhaps looks something like:
# This type of code would often be inside a loop if 'key' not in example: example['key'] = 0 # add key and initial value to dict; could also be a list example['key'] += 1 # this is implementing a counter
defaultdict can also be used with complex data types such as list and set :
>>> example = defaultdict(list) >>> example['key'].append(1) >>> example defaultdict(, )
Adding an element automatically initialises the list.