-1

I am looking to put 2 dictionaries into one dictionary. note. I am not looking to merge them or join them. I am looking for a method similar append for dictionary. Note; I want them to hold their structures. don't want the data to mix up

Example I Have this,

dic1 = {'Apple':'Mac', 'Microsoft': 'Surface', 'Google': 'Chromebook', 'Lenovo':'ThinkPad'}
dic2 = {1:'Apple', 2:'Amazon', 3:'Microsoft', 4:'Google', 5:'Facebook'}

I want this

dic3 = {{'Apple':'Mac', 'Microsoft': 'Surface', 'Google': 'Chromebook', 'Lenovo':'ThinkPad'},
{1:'Apple', 2:'Amazon', 3:'Microsoft', 4:'Google', 5:'Facebook'}}

Thanks in advance

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
jrl
  • 27
  • 1
  • 5

2 Answers2

0

Update: check the added example at the bottom.

If you don't want to change dic1 or dic2, you can do this:

dic3 = {**dic1, **dic2}

dic3 will be a dictionary.

Any common key will have the value appearing later (to the right).

For the type of output you expect (set of dictionaries), you need to create a hashable dictionary as follows:

class hashabledict(dict):
    def __hash__(self):
        return hash(tuple(sorted(self.items())))

dic1 = {'Apple':'Mac', 'Microsoft': 'Surface', 'Google': 'Chromebook', 'Lenovo':'ThinkPad'}
dic2 = {1:'Apple', 2:'Amazon', 3:'Microsoft', 4:'Google', 5:'Facebook'}
dic3 = {hashabledict(dic1), hashabledict(dic2)}

The above hashabledict class definition has been taken from here: Python hashable dicts

Tuhin Paul
  • 558
  • 4
  • 11
  • The OP does not want to merge/join the dictionaries, i.e. this answer is wrong. – mrzo Mar 10 '20 at 00:42
  • For the type of output he is asking, he needs to create a hashable dictionary; then he can proceed with assigning them to the set. – Tuhin Paul Mar 10 '20 at 01:01
  • Creating a hashable dictionary like this is an exceedingly bad idea. If you modify the dictionary after adding it to a set or using it as a key in another dictionary, you will break that container. Its operations simply won't make any sense afterwards. – Blckknght Mar 10 '20 at 01:37
  • Okay. The point was to match the output. Give an exceedingly good idea. – Tuhin Paul Mar 10 '20 at 04:16
0

That's not how dictionaries work. You can have a list or tuple (or possibly a frozenset) that looks mostly like what you want, but dictionaries do not allow this kind of linear concatenation. They are strictly associative containers, meaning that every value must have an associated key.

If you can associate each dictionary with a key, however, then what you want becomes extremely straightforward:

dic3 = {
    'dic1': {'Apple':'Mac', 'Microsoft': 'Surface', 'Google': 'Chromebook', 'Lenovo':'ThinkPad'},
    'dic2': {1:'Apple', 2:'Amazon', 3:'Microsoft', 4:'Google', 5:'Facebook'}
}

Or, using your variables:

dic3 = {'dic1': dic1, 'dic2': dic2}
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79