est ici un one-liner (imports
ne compte pas :) qui peut facilement être généralisé à concaténer dictionnaires N, Python 2.6+:
from itertools import chain
dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3))
Sortie:
>>> from itertools import chain
>>> d1={1:2,3:4}
>>> d2={5:6,7:9}
>>> d3={10:8,13:22}
>>> dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
{1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}
Généralisée à concaténer N dicts:
from itertools import chain
def dict_union(*args):
return dict(chain.from_iterable(d.iteritems() for d in args))
Je suis un peu en retard à cette fête, je sais, mais je ope cela aide quelqu'un.
Au lieu de 'd4 = dict (d1) 'on pourrait utiliser' d4 = copier (d1) '. –
@ds: Cela ne semble pas fonctionner. Peut-être que vous vouliez dire 'copie d'importation de copie; d4 = copier (d1) 'ou peut-être' d4 = d1.copy() '. –
La première version ne fonctionne pas sur Python3. – Superbest