Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "extend" for a dictionary

What is the best way to extend a dictionary with another one while avoiding the use of a for loop? For instance:

>>> a = { "a" : 1, "b" : 2 } >>> b = { "c" : 3, "d" : 4 } >>> a {'a': 1, 'b': 2} >>> b {'c': 3, 'd': 4} 

Result:

{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 } 

Something like:

a.extend(b)  # This does not work 
like image 910
FerranB Avatar asked Feb 23 '09 10:02

FerranB


People also ask

Can you use extend on a dictionary Python?

In Python, there is no extend() function in the dictionary but we can apply this method in lists and tuples. In Python, the update() function is used to modify the dictionary and by using this method we can concatenate the old dictionary to a new dictionary.

Can dictionary be extended?

A dictionary is a container of data that can be changed (is mutable), and it stores this data in the form of key-value pairs example {key: 'value'} . You can extend a dictionary with another element by concatenation. It means all the key-value pairs in one dictionary will be added to the other one.

What does extend () do in Python?

The extend() method adds the specified list elements (or any iterable) to the end of the current list.

Can you get the length of a dictionary in Python?

To calculate the length of a dictionary, we can use the Python built-in len() method. The len() method returns the number of keys in a Python dictionary.


1 Answers

a.update(b) 

Latest Python Standard Library Documentation

like image 172
Nick Fortescue Avatar answered Sep 19 '22 22:09

Nick Fortescue