0

I am looking to merge two dictionaries with the key as months and the values as a list of 12 values in both dictionaries. How do I merge the two dictionaries so that it does not sort into alpha order based on key. I simply want to add my second dictionary (with months June - December as keys) onto the end of my first dictionary (with months January to May as keys).

I have tried using the .concat and .append but I seem to be doing something wrong and it is sorting values.

Thanks

1
  • 2
    What do you mean by "it is sorting values"? You can use .update if they don't share common keys. Commented Jun 11, 2019 at 13:33

1 Answer 1

3

Use update function:

a = {1: 2, 2: 3}
b = {3: 4, 4: 5}
a.update(b)
a

{1: 2, 2: 3, 3: 4, 4: 5}


P.S. Note that dictionaries in Python are unordered. You can't rely on the keys order. If you want to use the ordered dictionary, you should use OrderedDict from collections module.

2
  • 3
    Note, that order is important for the OP and this solution will only officially work in python3.7+ where dicts are in insertion order. Commented Jun 11, 2019 at 13:35
  • I was updating my answer with more info about orders in this moment :)
    – vurmux
    Commented Jun 11, 2019 at 13:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.